IneasystepsisanimprintofInEasyStepsLimited
16HamiltonTerrace·HollyWalk·LeamingtonSpaWarwickshire·CV324LY
www.ineasysteps.com
Copyright©2015byInEasyStepsLimited.Allrightsreserved.Nopartofthisbookmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageorretrievalsystem,withoutpriorwrittenpermissionfromthepublisher.
NoticeofLiability
Everyefforthasbeenmadetoensurethatthisbookcontainsaccurateandcurrentinformation.However,InEasyStepsLimitedandtheauthorshallnotbeliableforanylossordamagesufferedbyreadersasaresultofanyinformationcontainedherein.
Trademarks
Alltrademarksareacknowledgedasbelongingtotheirrespectivecompanies.
Contents1Gettingstarted
Programmingcode
Settingup
ExploringIDLE
Gettinghelp
Savingprograms
Storingvalues
Addingcomments
Namingrules
Summary
2SavingdataStoringinput
Controllingoutput
Recognizingtypes
Convertingdata
Guessinggame
Correctingerrors
Summary
3PerformingoperationsDoingarithmetic
Assigningvalues
Comparingvalues
Findingtruth
Testingcondition
Settingorder
Summary
4MakinglistsWritinglists
Changinglists
Fixinglists
Settinglists
Namingelements
Summary
5ControllingblocksBranchingchoices
Countingloops
Loopingconditions
Skippingloops
Catchingerrors
Summary
6CreatingfunctionsDefiningblocks
Addingparameters
Returningresults
Storingfunctions
Importingfunctions
Summary
7SortingalgorithmsCopyingsorts
Selectingsorts
Insertingsorts
Bubblingsorts
Mergingsorts
Partitioningsorts
Summary
8ImportinglibrariesInspectingPython
Doingmathematics
Calculatingdecimals
Tellingtime
Runningtimers
Summary
9ManagingtextManipulatingstrings
Formattingstrings
Modifyingstrings
Accessingfiles
Manipulatingcontent
Updatingcontent
Summary
10ProgrammingobjectsDefiningclasses
Copyinginstances
Addressingproperties
Derivingclasses
Overridingmethods
Applyingsense
Summary
11BuildinginterfacesLaunchinginterfaces
Respondingbuttons
Displayingmessages
Gatheringentries
Listingoptions
Pollingradios
Checkingboxes
Addingimages
Summary
12DevelopingappsGeneratingrandoms
Planningneeds
Designinglayout
Assigningstatics
Loadingdynamics
Addingfunctionality
Testingprograms
Deployingapplications
Summary
13TransferringskillsUnderstandingcompilers
Compilingcode
CodingC
CodingC++
CodingC#
CodingJava
Summary
PrefaceThecreationofthisbookhasprovidedme,MikeMcGrath,awelcomeopportunitytoproduceanintroductiontocodingcomputerprogramsforreaderswithnopreviouscodingexperience.Althoughthisisabookforbeginners,itgoesbeyondthemerebasicssosometopicsmaybemoreeasilyunderstoodaftergainingsomecodingexperiencewiththesimplerlistedprograms.AlltheexamplesdemonstratecodingfeaturesusingthepopularPythonprogramminglanguageandthebook’sscreenshotsillustratetheactualresultsproducedbyexecutingthelistedcode.
Conventionsinthisbook
Inordertoclarifythecodelistedinthestepsgivenineachexample,IhaveadoptedthesamedefaultcolorizationconventionprovidedbyPython’scodeeditor.KeywordsofthePythonlanguageitselfarecoloredorange,built-infunctionnamesarepurple,coder-specifiedfunctionnamesareblue,textstringsaregreen,commentsarered,andallothercodeisblack,likethis:#Afunctiontodisplayagreeting
defgreet(reader):print(‘WelcometoCodingforBeginners’,reader)
Additionally,inordertoidentifyeachsourcecodefiledescribedinthesteps,aniconandfilenameappearsinthemarginalongsidethesteps,likethis:
program.py
Grabbingthesourcecode
ForconvenienceIhaveplacedsourcecodefilesfromtheexamplesfeaturedinthisbookintoasingleZIParchive.Youcanobtainthecompletearchivebyfollowingtheseeasysteps:
Browsetowww.ineasysteps.comthennavigatetoFreeResourcesandchoosetheDownloadssection
FindCodingforBeginnersineasystepsinthelist,thenclickonthehyperlinkentitledAllCodeExamplestodownloadthearchive
Now,extractthearchivecontentstoanyconvenientlocationonyourcomputer
1Gettingstarted
Welcometotheexciting,funworldofcomputercoding!Thischapterdescribeshowtocreateyourownprogramming
environmentanddemonstrateshowtocodeyourveryfirstprogram.
ProgrammingcodeSettingupExploringIDLEGettinghelpSavingprogramsStoringvaluesAddingcommentsNamingrulesSummary
ProgrammingcodeAcomputerismerelyamachinethatcanprocessasetofsimpleinstructionsveryquickly.Thesetofinstructionsitprocessesisknownasa“program”,andtheinstructionsareknownas“code”.
Peoplewhowritecomputerprogramsareknownas“programmers”or“coders”.Theirprogramshaveenabledcomputerstobecomeusefulinalmosteveryareaofmodernlife:
• Inthehand–computersarefoundincellphonedevicesfortaskssuchascommunicationviavoice,text,andsocialmedia
• Inthehome–computersarefoundinhouseholddevicessuchasTVsets,gamingconsoles,andwashingmachines
• Intheoffice–computersarefoundindesktopdevicesfortaskssuchaswordprocessing,payroll,andgraphicdesign
• Inthestore–computersarefoundinretaildevicessuchasautomatictellermachines(ATMs)andbarcodescanners
• Inthecar–computersarefoundincontroldevicesfortaskssuchasenginemanagement,anti-lockbrakingandsecurity
• Inthesky–computersarefoundinairplanesforpilotingandinairtrafficcontrolcentersforsafenavigation
Theseare,infact,justafewexamplesofhowcomputersaffectourlivestoday.Yet,computersarereallydumb!Theycanonlycountfromzerotoone,andcannotthinkforthemselves.
Acomputerisacollectionofelectroniccomponents–collectivelyknownas“hardware”.Tomakethecomputerfunctionitmustbegivenasetofprograminstructions–knownas“software”.
Itisimportantthateachcomputerprogramprovidesclearstep-by-stepinstructionsthatthecomputercanexecutewithouterrors.Thecodermustthereforebreakdownthetaskrequiredofthecomputerintosimpleunambiguoussteps.Forexample,aprogramtomoveamobilerobotfromindoorstooutdoorsmustincludeinstructionstohavetherobotlocateadoorwayandnavigatearoundanyobstacles.Sothecodermustalwaysconsiderwhatpossibleunexpecteddifficultiesaprogrammayencounter.
Programinstructionsmustbepresentedtothecomputerinalanguageitcanunderstand.Atthemostbasiclevelthecomputercanunderstand“machinecode”,whichmovesitemsaroundinitsmemorytoperformtasks.Thistypeofobscurelow-levelcodeisincredibly
tediousasitrequiresmanylinesofinstructiontoperformevenasimpletask.
Fortunately,overtheyears,many“high-level”programminglanguageshavebeendevelopedthatallowthecodertocomposeinstructionsinmorehuman-readableform.Thesemodernhigh-levelprogramsareautomaticallytranslatedintothemachinecodethatthecomputercanunderstandbya“compiler”orbyan“interpreter”.Inordertobecomeacoderyoumusttypicallylearnatleastoneofthesehigh-levelprogramminglanguages:
• C–apowerfulcompiledlanguagethatiscloselymappedtomachinecodeandusedtodevelopoperatingsystems
• C++–anenhancedcompiledlanguagedevelopingonCtoprovideclassesforObjectOrientedProgramming(OOP)
• C#–amoderncompiledlanguagedesignedbyMicrosoftforthe.NETframeworkandCommonLanguageInfrastructure
• Java–aportablecompiledlanguagethatisdesignedtorunonanyplatformregardlessofthehardwarearchitecture
• Python–adynamicinterpretedlanguagethatallowsbothfunctionalandObjectOrientedProgramming(OOP)
Programswritteninaninterpretedlanguagecanberunimmediatelybutthosewrittenincompiledlanguagesmustfirstbecompiledbeforetheycanberun.
Justashumanlanguageshavesimilarities,suchasverbsandnouns,theseprogramminglanguageshavecertainsimilaritiesastheyeachpossess“datastructures”,inwhichtostoreinformation,and“controlstructures”thatdeterminehowtheprogramproceeds.
TheexamplesinthisbookusethePythonlanguagetodemonstratehowtocodecomputerprogramsasithasasimplelanguagesyntax,requiresnocompilation,includesalargelibraryofstandardfunctions,andcanbeusedtocreatebothConsoleprogramsandwindowedGUI(GraphicalUserInterface)apps.
Pythonisatotalpackageof“batteriesincluded”.
SettingupBeforeyoucanbegincodingprogramsinthePythonlanguageyouneedtosetupaprogrammingenvironmentonyourcomputerbyinstallingthePythoninterpreterandthestandardlibraryoftestedcodemodulesthatcomesalongwithit.ThisisavailableonlineasafreedownloadfromthePythonSoftwareFoundation.
Launchawebbrowserandnavigatetopython.org/downloadsthenclicktheDownloadsbuttontograbthelatestversionforyoursystem–inthiscaseit’s“Python3.4.2”
Whenthedownloadcompletesruntheinstallerandchoosewhethertoinstallforallusersorjustyourself,thenclicktheNextbuttontoproceed
Now,acceptthesuggesteddefaultinstallationlocation,whichwillbeadirectoryonyourrootC:\drivenamed“Python”andversionnumber–inthisexampleit’sadirectoryatC:\Python34forPythonversion3.4.2
InstallersforMacOSXandOtherPlatformsarealsofreelyavailableatpython.org/downloads
Doacceptthesuggesteddestinationdirectory–suchasC:\Python34thatissuggestedhere.
ClicktheNextbuttontoproceedthenbesuretoselectthefeatureto“Addpython.exetoPath”
ClickonNexttobegincopyingfilesontoyourcomputerthenclicktheFinishbuttontocompletetheinstallation
UponcompletionthePythongroupisaddedtoyourStart/Appsmenu.MostimportantofthisgroupistheIDLEitemthatlaunchesthePythonintegrateddevelopmentenvironment.
AddingPythontothesystemPathmakesitavailablefromwithinanydirectory.Afterinstallation,youcanexactlyenterthecommandpython-VataCommandPrompttoseetheinterpreterrespondwithitsversionnumber.
YouwillusetheIDLElauncheroftensoright-clickonitsiconandchoose“Pintotaskbar”tomakeitreadilyavailablefromtheWindowsDesktop.
ExploringIDLETheinstalledPythonsoftwarepackageincludestheIntegratedDeveLopmentEnvironment(IDLE)inwhichyoucaneasilycodeandrunprograms,orsnippets,writteninthePythonlanguage.IDLEprovidestwodifferentwindowsforprogramdevelopment:
• ShellWindow
• EditWindow
WhenyoustartupIDLEitopensanewwindowcontainingamenubar,abannerdescribingtheversion,anda>>>prompt.ThisistheShellWindowinwhichyoucaninteractdirectlywiththePythoninterpreterbyenteringstatementsattheprompt.
Iftheinterpreterunderstandsyourentryitwillrespondwithanappropriatereply,otherwiseitwillreportanerror.
YoucanmaketheinterpreterprintoutastringoftextbyenteringaPythonprint()functionstatementthatenclosesyourstringwithinquotemarksinsidetheparenthesesattheinteractiveprompt.
Mostprogramminglanguagesrequiretextstringstobeenclosedinquotemarkstodifferentiatethemfromprogramcode.Byconvention,Pythoncodersusesinglequotes.
Youcanalsomaketheinterpreterprintouttheresultofasimplearithmeticsumbyenteringavalidsumstatementattheprompt.
Ifyourstatementisnotvalid,suchasasumthatattemptstodivideanumberbyzero,theinterpreterwillprintoutanerrormessagehelpfullydescribingthenatureoftheerror.
OpenanIDLEShellWindowthenpreciselyenterthisstatementattheinteractivepromptprint(‘HelloWorld!’)
Next,hittheReturnkeytoseetheinterpreter’sresponse
Now,enterthissumstatementattheinteractiveprompt
8+4
Spacesinstatementsareignored–so8+4canbeenteredwithoutspaces.
HitReturntoseetheinterpreterprinttheresulttotal
Enterthisinvalidstatementattheinteractiveprompt
8/0
HitReturntoseetheinterpreterprintanerrormessage
TheShellWindowismostlyusedtotestsnippetsofcode.
GettinghelpTheIDLEShellWindowprovidesagreatHelputilitywhereyoucanfindhelponanyPythontopicwhencodingPythonprograms.HelpcanbesoughtbyenteringaPythonhelp()statementattheinteractive>>>prompt.Awelcomemessageappearsandthepromptchangestohelp>todenoteyouarenowinHelpmode.
OpenanIDLEShellWindowthenpreciselyenterthisstatementattheinteractiveprompthelp()
Next,hittheReturnkeytoenterHelpmode
Now,enterthistopicnameattheHelputilitypromptkeywords
HitReturntolistallkeywordsofthePythonlanguage
TheHelputilitywelcomemessagealsocontainshandyhints–butareomittedhereforbrevity.
Keywordsarethevocabularyofaprogramminglanguage.NotethatPythonkeywordsarecase-sensitive–theseareallinlowercaseexceptFalse,None,andTrue.
Then,enterthiscommandattheHelputilitypromptquit
HitReturntoexitHelpandreturntoaninteractiveShellWindowprompt
Therearenoparenthesesrequiredafterthequitinstruction–hereitisaHelputilitycommand,notaPythonstatement.
Whenyoujustwanthelponasingletopicyoucansimplyenterthetopicnamewithinquotemarksinsidetheparenthesesofahelp()statementattheinteractiveprompt:
Preciselyenterthisstatementattheinteractiveprompt
help(‘keywords’)
HitReturntolistallkeywordsofthePythonlanguageandremainataninteractiveShellWindowprompt
Keywordshavespecialmeaninginaprogramminglanguage–theycannotbeusedtonameitemsinyourcode.
SavingprogramsTheIDLEShellWindow,describedonthepreviouspage,isagreatplacetotryoutsnippetsofcode,butcannotsaveyourcode.HappilyIDLEalsoprovidesanEditWindowwhereyoucancreatelongerpiecesofprogrammingcodethatcanbestoredina(.py)fileonyourcomputer.Thismeansyoucaneasilyre-runthecodewithoutre-typingalltheinstructionsattheShellWindow>>>promptandthisletsyouedityourcodetotrynewideas.Theproceduretocreate,save,andrunyourcodelookslikethis:
• OpenanEditWindowfromtheShellWindowbyselectingFile,NewFilefromtheShellWindowmenuitems–orbypressingtheCtrl+Nshortcutkeys
• TypecodeintotheEditWindowthensaveitbyselectingFile,SavefromtheEditWindowmenuitems–orbypressingtheCtrl+Sshortcutkeys
• RunsavedcodefromtheEditWindowbyselectingRun,RunModulefromtheEditWindowmenuitems–orbypressingtheF5shortcutkey
Theproceduredescribedherewillbeusedtodemonstratethecodeexamplesgiventhroughoutthisbook.
OutputfromyourprogramcodewillappearintheShellWindowastheprogramruns,orahelpfulerrormessagewillappearthereiftheinterpreterdiscoversanerrorinyourcode.
OpenanIDLEShellWindowthenselecttheFile,NewFilemenuitemtoopenanIDLEEditWindow
NoticetheFile,OpenandFile,RecentFilesmenuitemsthatcanbeusedtore-runprogramcodepreviouslysaved.
helloworld.py
Now,intheIDLEEditWindow,preciselyenterthiscode
print(‘HelloWorld!’)
Next,intheIDLEEditWindow,selecttheFile,Savemenuitems,toopentheSaveAsdialog,thensaveyourprogramcodeasafilenamedhelloworld.py
Finally,intheIDLEEditWindow,selecttheRun,RunModulemenuitems,torunyourprogramcodeandseetheoutputappearintheShellWindow
Yourprogramcodecanbesavedatanyconvenientlocationonyourcomputer–hereitissavedinadirectorycreatedatC:\MyCodethatwillbeusedforallexamplesinthisbook.
NoticethattheShellWindowrestartswheneveritrunsyourprogramcodeafresh.
StoringvaluesOneessentialfeatureofallcomputerprogramminglanguagesistheabilitytostoredatavaluesintheprogramcode.Thisabilityisprovidedbyasimpledatastructurecalleda“variable”.Avariableisacontainerinwhichanitemofdatacanbestored,muchlikeareal-lifeobjectcanbestoredinabox.
Whencreatingavariableyougiveitanameofyourchoice,subjecttothenamingconventionsoftheprogramminglanguage,thatactslikealabelonabox.Thedataitemstoredwithinthevariablecansubsequentlyberetrievedusingitsgivenname–justasyoucanfindareal-lifeobjectinaboxbyreadingitslabel.
DatatobestoredinavariableisassignedinaPythonprogramdeclarationstatementwiththe=assignmentoperator.Forexample,tostorethenumericvalueeightinavariablenamed“a”:a=8
Thestoredvaluecanthenberetrievedusingthevariable’sname,sothatthestatementprint(a)willoutputthestoredvalue8.Thatvariablecansubsequentlybeassignedadifferentvalue,soitsvaluecanvaryastheprogramproceeds–hencetheterm“variable”.
InPythonprogrammingavariablemustbeassignedaninitialvalue(“initialized”)inthestatementthatdeclaresitinaprogram–otherwisetheinterpreterwillreporta“notdefined”error.
Multiplevariablescanbeinitializedwithacommonvalueinasinglestatementusingasequenceof=assignments.Forexample,toinitializevariablesnamed“a”,“b”and“c”eachwithanumericvalueofeightlikethis:a=b=c=8
Someprogramminglanguages,suchasJava,demandyouspecifyinitsdeclarationwhattypeofdataavariablemaycontain.Thisreservesaspecificamountofmemoryspaceandisknownas“statictyping”.Pythonvariables,ontheotherhand,havenosuchlimitationandadjustthememoryallocationtosuitthevariousdatavaluesassignedtotheirvariables(“dynamictyping”).Thismeanstheycanstoreintegerwholenumbers,floating-pointnumbers,textstrings,orBooleanvaluesofTrueorFalseasrequired.
Programminglanguagesthatrequirevariabletypestobespecifiedare
alternativelyknownas“stronglytyped”,whereasthosethatdonotarealternativelyknownas“looselytyped”.
firstvar.py
OpenanIDLEEditWindowthenentercodetocreateavariablenamed“var”tostoreawholenumberintegervar=8
Next,addastatementtodisplaythestoredintegervalue
print(var)
Assignanewfloating-pointnumbertothevariablethenaddastatementtodisplaythestoredfloatvaluevar=3.142
print(var)
Now,assignatextstringtothevariablethenaddastatementtodisplaythestoredstringvaluevar=‘CodingforBeginnersineasysteps’print(var)
Finally,assignalogicaltruthvaluetothevariablethenaddastatementtodisplaythestoredBooleanvaluevar=True
print(var)
Savethefile(File,Save)thenruntheprogram(Run,RunModule)toseethestoredvaluesdisplayedinoutput
Textstringdatamustbeenclosedwithinquotemarkstodenotethestartandendofthatparticularstring.
AddingcommentsWhenyoubegintocodelongerprogramsitisusefultoaddcommentsatthestartofeachpieceofcodedescribingthepurposeofthatpiece.Thismakesthecodemoreeasilyunderstoodbyothers,andbyyourselfwhenrevisitingthecodeatalaterdate.InthePythonprogramminglanguageeverythingonasinglelineaftera#hashcharacterisignoredbytheinterpreter.Thismeansthatasingle-linecommentcanbeinsertedaftera#character.
comment.py
OpenanIDLEEditWindowthenentercommentedcodetoinitializeavariableanddisplayitsstatus#Initializeprogramstatus
running=Trueprint(‘Runstate:‘,running)
Savethefilethenruntheprogramtoseethecommentgetignoredandthestoredvaluedisplayedinoutput
Toreadilyidentifyaspectsofyourcode,IDLEautomaticallycolorizesyourcode,bothintheShellWindowandtheEditWindow,withthedefaultcolorslistedinthetablebelow:
CodelistedinthestepsthroughoutthisbookalsousethedefaultIDLEcolorsfor
Namingrules
Keywords:
False None True
and as assert
break class continue
def del elif
else except finally
for from global
if import in
is lambda nonlocal
not or pass
raise return try
while with yield
Itisgoodprogrammingpracticetochoosemeaningfulnamesthatreflectthenatureofthevariable’scontent.
Variablecontainersthatyoucreateinyourcodetostoredatawithinaprogramcanbegivenanynameofyourchoosing–providingyoudonotuseanyoftheprogramminglanguagekeywords,suchasthePythonkeywordsinthetableabove,andthenameadherestothenamingruleslistedinthetablebelow:
Namingrule: Example:
CANNOTcontainanykeywords True
CANNOTcontainarithmeticoperators a+b*c
CANNOTcontainsymbols %$#@!
CANNOTcontainanyspaces nospaces
CANNOTstartwithanumber 2bad
CANcontainnumberselsewhere good1
CANcontainlettersofmixedcase UPdown
CANcontainunderscores is_ok
Variablenamesarecase-sensitiveinPython–sovariablesnamed“VAR”,“Var”,and“var”wouldbetreatedasthreeseparatevariables.
Summary• Acomputerprogramisasetofinstructions,writtenbyacoder,thatenablecomputers
tobecomeuseful
• Theelectroniccomponentsofacomputerareitshardware,whereasprograminstructionsareitssoftware
• Computersunderstandlow-levelmachinecode
• High-levelprogramminglanguagesinhuman-readableformgetautomaticallytranslatedintolow-levelmachinecode
• Programminglanguagespossessdatastructurestostoreinformationandcontrolstructurestodetermineprogress
• ThePythonprogramminglanguagehassimplesyntax,requiresnocompilation,andincludesalibraryoffunctions
• Python’sdevelopmentenvironmentiscalledIDLE
• IDLEprovidesaShellWindowcontaininganinteractivepromptfortestingandanEditWindowforcodingprograms
• TheIDLEHelputilityisaccessedbyenteringahelp()statementataShellWindowprompt
• AftertypingprogramcodeintoanIDLEEditWindowitmustfirstbesavedasafilebeforetheprogramcanberun
• OutputfromaprogramrunfromtheEditWindowappearsintheShellWindow,orahelpfulerrormessageappearsthere
• Avariabledatastructureisanamedcontainerthatallowsasingleitemofdatatobestoredforusebyaprogram
• Datastoredinavariablecanberetrievedusingthatvariable’snameandmaybereplacedbyassigninganewvalue
• VariablesinPythonprogrammingcanstoreanytypeofdata
• Commentlinescanusefullybeaddedtoprogramcodeafterbeginningthelinewitha#hashcharacter
• Variablenamesmustnotuseanyoftheprogramminglanguagekeywordsandmustadheretoitsnamingrules
2Savingdata
Thischapterdemonstrateshowtocreatecodetousevarioustypesofdatastoredinsideyourprograms.
StoringinputControllingoutputRecognizingtypesConvertingdataGuessinggameCorrectingerrorsSummary
StoringinputTheabilitytostoreandreplacecodedprogramdatainavariableisgreat,butthisabilitycanalsobeusedtostoredatainputbyauser–allowingyourprogramstobecomeinteractive.
InPythonprogrammingabuilt-ininput()functioncanbeusedtoacceptuserinputfromakeyboardandassignittoavariable.Optionally,thisfunctioncanspecifyastring,withinquotemarksinsideitsparentheses,thatwillbedisplayedtorequesttheinput.TheprogramwillwaituntiltheuserhitstheReturnkeybeforeassigningtheirinputtothevariableandproceedingonwards.
Storedvariablevaluescanbeoutputbythebuilt-inprint()functionbyspecifyingthevariablenamewithinthefunction’sparentheses.Multiplevaluesmayalsobespecifiedforoutputasacomma-separatedlistwithintheparentheses.
input.py
OpenanIDLEEditWindowthenenterthiscodetorequestuserinputwithwhichtoinitializeavariablename=input(‘Pleaseenteryourname:‘)
Next,addastatementtooutputbothastringandthevaluestoredwithinthevariableprint(‘Hello’,name)
Now,addstatementstooutputastringthenbothastringandthevaluestoredwithinthevariableoncemoreprint(‘WelcometoCodingforBeginners’)
print(‘Remembertohavefun’,name,‘!’)
Savethenruntheprogram,enteryournamewhenrequested,andhitReturntoseeyournameintheoutput
Thereisnoneedtoincludespacesinthecomma-separatedlists–theyareignoredbytheinterpreterbutareshownhereforclarity.
ControllingoutputAstheexampleonthefacingpagedemonstrates,avaluestoredinavariableremainsavailableforrepeateduseuntilitisreplacedbyanewvalueoruntiltheprogramends.
Therearealsotwopointsworthnotingwithregardtothisexample’soutput.Firstly,theprint()functionautomaticallyaddsaninvisible\nnewlinecharacterafteritsoutput–sothenextprint()functionoutputwillbydefaultappearonthenextlinebelow.Secondly,theprint()functionautomaticallyaddsaspacebetweeneachitemwhenacomma-separatedlistisspecifiedforoutput.
Youcanoverridetheautomaticnewlinebehaviorbyspecifyingthatthelineshouldendwithaspace,ratherthanthe\ndefault.Youcanalsoavoidtheautomaticspacingbehaviorby“concatenating”itemswitha+symbol,ratherthanacomma.
concat.py
OpenanIDLEEditWindowthenenterthiscodetorequestuserinputwithwhichtoinitializeavariablename=input(‘Pleaseenteryourname:‘)
Next,addastatementtooutputastringandthevaluestoredwithinthevariable–butwithoutafinalnewlineprint(‘Hello’+name,end=‘‘)
Now,addstatementstooutputastringthenastringconcatenatedtothevaluestoredwithinthevariableprint(‘WelcometoCodingforBeginners’)
print(‘Remembertohavefun’+name+‘!’)
Savethenruntheprogram,enteryournamewhenrequested,andhitReturntoseecontrolledoutput
RecognizingtypesTherearefouressentialtypesofdatayoucanrepresentwhencodingacomputerprogramandthatcanbestoredinvariables.AlthoughvariablesinthePythonlanguagecanstoreanytypeofdataitisimportanttounderstandthedifferenttypesasyouwillsometimesneedtoconvertfromonetypetoanotherinyourcode:
Datatype: Description: Example:
str Astringofcharacters,whichcanincludeletters,numbers,spaces,andsymbols
‘Daytona500’
int Anintegerwholenumber,whichDOESNOThaveadecimalpointpart 1000
float Afloating-pointnumber,whichDOEShaveadecimalpointpart 98.6
bool ABooleanlogicaltruthvalue,whichiseitherTrueorFalse True
Integerintnumbersshouldnotincludeanypunctuation–socodeonethousandas1000ratherthan1,000.
Stringsaresimplyanycollectionofcharactersyoucanenterfromthecomputerkeyboard,groupedtogetherwithinquotemarks.Variablesrecognizeavaluebeingassignedtoitasbelongingtothestr“class”ifthatvalueisenclosedwithinquotemarks.
Stringstrvaluesmustalwaysbeenclosedwithquotemarks.Numbersareanynumericvalueyoucanenterfromthekeyboardbutaredefinedbytheinclusionoromissionofadecimalpoint.Variablesrecognizeanumericvaluebeingassignedtoitasbelongingtotheint“class”ifthatvaluehasnodecimalpointorasbelongingtothefloatclassifitdoesindeedhaveadecimalpoint.
Booleansarealogicaltruthvalue.VariablesrecognizeaBooleanvaluebeingassignedtoitasbelongingtothebool“class”bythekeywordsTrueandFalse,orifthatvalueevaluatestoTrueorFalse.
InPythonprogrammingyoucaneasilydiscoverthetypeofdatastoredwithinavariablebyspecifyingthatvariable’snamewithintheparenthesesofthebuilt-intype()function.
types.py
OpenanIDLEEditWindowandinitializeavariablebyassigningitastring,thendisplayitsvalueanddatatyperace=‘Daytona500’
print(race,‘is‘+type(race))
Next,initializeavariablebyassigningitawholenumberthendisplayitsvalueanddatatypekilo=1000print(kilo,‘is‘+type(kilo))
Now,initializeavariablebyassigningitadecimalnumber,thendisplayitsvalueanddatatypetemp=98.6
print(temp,‘is‘+type(temp))
Initializeavariablebyassigningitatruthkeywordthendisplayitsvalueanddatatypeflag=Trueprint(flag,‘is‘+type(flag))
Finally,replacethelastvariablevaluewithatruthresultofacomparison,thenagaindisplayitsvalueanddatatypeflag=4>8
print(flag,‘is‘+type(flag))
Savethenruntheprogramtodiscoverthetypesofdatastoredwithinthevariablesyouhavecreated
Thecomparisonhereexamineswhether4isgreaterthan8,whichisofcourseuntrue.Comparisonsaredemonstratedfullyinthenextchapter.
ConvertingdataOftenyouwillneedtoconvertdatainyourprogramstoperformsomekindofmanipulation–suchasarithmeticorconcatenation.Arithmeticcanonlybeperformedonnumericdatatypes,suchasintandfloatdata,whereasconcatenationcanonlybeperformedonstringdatatypes,suchasstrdata.
Pythonprovidesseveralbuilt-infunctionsthatallowyoutoeasilyconvertdatainyourprogramstoadifferentdatatype.Thesedonotconverttheoriginalspecifiedvalueitselfbutmerelyreturnaconvertedrepresentationofitsvalue.Inprogrammingtermsthisisknownasa“cast”operation:
Function: Description:
int(x) Convertsxtoanintegerwholenumber
float(x) Convertsxtoadecimalfloating-pointnumber
str(x) Convertsxtoastringrepresentation
Numericvaluesinyourcodeshouldnotbeenclosedwithinquotemarks–numberswithinquoteswillbeseenasstringvalues!
Numericvaluesassignedtovariablesmanuallyinyourcodeareautomaticallyappointedtheappropriatedatatypeofintorfloat.Valuesassignedtovariablesfromusersbythebuilt-ininput()functionare,however,alwaysautomaticallyappointedthestrstringdatatype–evenwhentheyaresimplynumericvalues!Thismeanstheymustbeconverted(cast)toanappropriatenumerictypeofintorfloatbeforeyoucanperformarithmeticwiththem.
Converselynumericvaluesassignedtovariablesmanuallyinyourcode,whichareautomaticallyappointedtheappropriatedatatypeofintorfloat,cannotbeconcatenatedintoastring.Thismeanstheymustbeconvertedtoastrdatatypeforinclusioninastring.
InPython,asinmanyotherprogramminglanguages,the+symbolhasmorethanonepurposeaccordingtoitscontext.Wherethe+symbolisusedbetweentwonumericvaluesitperformsanaddition(seenasan“additionoperator”)butwherethe+symbolisusedbetweentwostringvaluesitperformsaconcatenation(seenasa“concatenationoperator”).Variablesthatareassignedtheresultofeitherkindofoperationwillautomaticallybeappointedtheappropriatedatatypeoftheresult.
Arithmeticperformedonanintandfloatdatatypetogetherwillbeautomaticallycastintoafloatresult.Castvaluestothefloatdatatypetoallowfordecimalnumberinput.
cast.py
OpenanIDLEEditWindowandinitializetwovariablesbyassigningthemnumericuserinputnum1=input(‘Pleaseenterawholenumber:’)
num2=input(‘Nowenteranotherwholenumber:’)
Next,displaythedatatypeofeachvariabletoseethenumericvaluesare,infact,storedasstringsprint(‘Inputis:‘,type(num1),type(num2))
Now,usethe+operatortoattemptaddition,butseetheresultgetsconcatenatedasastrdatatypetotal=num1+num2print(‘Total:‘,total,type(total))
Again,usethe+operatortoattemptaddition,butcastthestoredvaluestoseetheresultasanintdatatypetotal=int(num1)+int(num2)
print(‘Total:‘,total,type(total))
Finally,castthestoredvaluesasafloatdatatypeandconcatenatethefloatresultvaluetotheoutputstrstringtotal=float(num1)+float(num2)print(‘Total:‘+str(total),type(total))
Savethenruntheprogramtoseethestoreddatatypesconvertedbycastingthemwiththebuilt-infunctions
Ifyouforgettoconverttothecorrectdatatypetheinterpreterwillreportanerror–tryaddinganinttoastrdatatypetoseetheerrormessage.
GuessinggameTheprevioussimpleexampleshaveillustratedhowvariablescanbeusedtostoretextstringvalues,numericintegerandfloating-pointdecimalvalues,andBooleantruthvaluesinyourprograms.Now,theycanbeusedtocreateaGuessingGameprogrambystoringarandomgeneratedintegerwhosevaluetheuserwillhavetoguess,aBooleantruthvaluethatwillendthegamewhentheuserguessescorrectly,andastringcontainingtheuser’sguess.
Thecodeinthisexampleincludessomefeaturesthatareonlydemonstratedlaterinthisbook,butasPythonisaneasilyhuman-readableprogramminglanguageyoushouldbeabletounderstandinprinciplehowthisprogramworks.
guess.py
OpenanIDLEEditWindowandbeginaprogrambyimportinga“random”libraryclassthatprovidesrandomnumbergeneratorfunctionsimportrandom
Now,initializethreevariables–ageneratedrandomnumberbetweenoneand20,aBooleanvaluethatwillremainTrueaslongasthegameisinprogress,andazerovaluethatwilllaterstoreanumberinputbytheusernum=random.randint(1,20)
flag=Trueguess=0
Next,displayamessageaskingtheusertomakeaguess
print(‘Guessmynumber1-20:‘,end=‘‘)
Then,preciselycopythiscodethatwillcomparethestoreduser’sguesstothestoredrandomnumberwhileflag==True:
guess=input()ifnotguess.isdigit():
print(‘Invalid!Enteronlydigits1-20‘)break
elifint(guess)<num:print(‘Toolow,tryagain:‘,end=‘‘)
elifint(guess)>num:print(‘Toohigh,tryagain:‘,end=‘‘)
else:print(‘Correct…Mynumberis‘+guess)
flag=False
Manyprogramlanguagesusecharacterssuchas{}togroupstatementstogetherbutPythonusesindentation–sotheindentationshownheremustbecorrectlypreserved.
Savethenruntheprogramandenterguessestoseeyourinputcomparedtoastoredrandomnumber
Noticethattheprogramrejectsuserinputofstrstringorfloatvalues.GuessingGameinPython–programanalysis
• Therandomlibraryclass’srandint()functionspecifiesanupperandlowerrandomrangewithinitsparentheses
• Theflagvariablespecifiesaninitialprogramconditionthatwillallowtheprogramtostartexaminingtheuser’sinput
• Thewhilekeywordspecifiesa“loop”controlstructurethatwillrepeatthestatementsitcontainsuntilatestedconditionfails
• Theifnotguess.isdigit()testspecifiesanactiontobreaktheloopiftheuserinputisnotanintegerwholenumber
• Theelifint(guess)<numtestspecifiesanalternativeactionifthecastuserinputislowerthanthestoredrandomnumber
• Theelifint(guess)>numtestspecifiesanalternativeactionifthecastuserinputishigherthanthestoredrandomnumber
• Theelsekeywordspecifiesafinalalternativeactiontochangetheprogramcondition,therebyendingtheprogram
Youneednotyetunderstandthisprogramindetail–eachaspectisexplainedbyexampleslaterinthisbook.
CorrectingerrorsWhencodingprogramstherearethreecommontypesoferrorthatcanoccur.ItisusefultorecognizethesedifferenterrortypesinPythonprogrammingsotheycanbecorrectedmoreeasily:
• SyntaxError–occurswhentheinterpreterencounterscodethatdoesnotconformtothePythonlanguagerules.Forexample,amissingquotemarkaroundastring.Theinterpreterhaltsandreportstheerrorwithoutexecutingtheprogram.
• RuntimeError–occursduringexecutionoftheprogram,atthetimewhentheprogramruns.Forexample,whenavariablenameislatermis-typedsothevariablecannotberecognized.Theinterpreterrunstheprogrambuthaltsattheerrorandreportsthenatureoftheerrorasan“Exception”.
• SemanticError–occurswhentheprogramperformsunexpectedly.Forexample,whenorderprecedencehasnotbeenspecifiedinanexpression.Theinterpreterrunstheprogramanddoesnotreportanerror.
Programmingerrorsareoftencalled“bugs”andtheprocessoftrackingthemdownisoftencalled“debugging”.
Correctingsyntaxandruntimeerrorsisfairlystraightforward,astheinterpreterreportswheretheerroroccurredorthenatureoftheerrortype,butsemanticerrorsrequirecodeexamination.
syntax.py
OpenanIDLEEditWindowthenaddastatementtooutputastringthatomitsaclosingquotemarkprint(‘CodingforBeginnersineasysteps)
Savethenruntheprogramtoseetheinterpreterhighlightthesyntaxerrorandindicateitsnature
TheredsyntaxerrorindicatorpointstothelinewheretheEndOfLine(EOL)erroroccurs.
Insertaquotemarkbeforetheclosingparenthesistoterminatethestringandsavethenruntheprogramagain–toseetheerrorhasbeencorrected
runtime.py
Next,beginanewprogrambyinitializingavariablethentrytooutputitsvaluewithanincorrectvariablename–toseetheinterpreterreportaruntimeerrortitle=‘CodingforBeginnersineasysteps’
print(titel)
Amendthevariablenametomatchthatinthevariabledeclarationandsavethenruntheprogramagain–toseetheerrorhasbeencorrected
semantic.py
Now,beginanewprogrambyinitializingavariablethentrytooutputanexpressionusingitsvaluewithoutexplicitprecedence–toseeapossiblyunexpectedresultof28
num=3
print(‘Result:‘,num*8+4)
Addparenthesestogrouptheexpressionas3*(8+4)thensavethefileandruntheprogramagain–toseetheexpectedresultof36,correctingthesemanticerror
DetailsofhowtohandleruntimeExceptionerrorsinyourscriptcodeareprovidedhere.
Summary• Variablescanbeusedtostoredatavaluesspecifiedinprogramcodeandtostoredata
valuesinputbyauser
• Avaluestoredinavariableremainsavailableforrepeateduseuntilitisreplacedbyanewvalueoruntiltheprogramends
• ThePythonbuilt-ininput()functioncanassigninputtoavariableandmayoptionallyspecifyastringtobedisplayed
• ThePythonbuilt-inprint()functioncanspecifymultiplevaluesforoutputasacomma-separatedlistinitsparentheses
• Bydefault,theprint()functionwillautomaticallyadda\nnewlineafteritsoutputunlessanendalternativeisspecified
• The+concatenationoperatorcanjointwostringstogether
• Datatypesareessentiallystrtextstrings,intintegernumbers,floatdecimalnumbers,orboolBooleantruthvalues
• BooleansarelogicaltruthvaluesthatarerepresentedinPythonbytheTrueandFalsekeywords
• ThePythonbuilt-intype()functioncanidentifytowhichclassdatatypeavalueinanyspecifiedvariablebelongs
• ValuesassignedtoavariablebythePythonbuilt-ininput()functionarealwaysappointedthestrstringdatatype
• DatatypescanbeconvertedformanipulationusingthePythonbuilt-inint(),float(),andstr()castingfunctions
• Arithmeticperformedonanintintegernumberandafloatdecimalnumberwillproduceafloatdatatyperesult
• Syntaxerrorsduetoincorrectcodearerecognizedbytheinterpreterbeforeexecutionoftheprogram
• Runtimeerrorsduetoexceptionsarerecognizedbytheinterpreterduringexecutionoftheprogram
• Semanticerrorsduetounexpectedperformancearenotrecognizedbytheinterpreter
3Performingoperations
Thischapterdemonstrateshowtouseoperatorsymbolsinyourcodestatements.
DoingarithmeticAssigningvaluesComparingvaluesFindingtruthTestingconditionSettingorderSummary
DoingarithmeticThearithmetical“operators”commonlyusedincodingcomputerprogramsusea+symbolforadditionanda-symbolforsubtraction,asyouwouldexpect.Typically,theyalsousean*asteriskformultiplication,ratherthananxsymbol,anda/forwardslashfordivision,ratherthana÷symbol.
ThearithmeticaloperatorsusedtocodePythonprogramsarelistedinthetablebelow,togetherwiththeoperationtheyperform:
Operator: Operation:
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
// Floordivision
** Exponent
The+operatoraddstwonumberstogetherandthe-operatorsubtractsthesecondnumberfromthefirstnumber.
The*operatormultipliesthefirstnumberbythesecondnumberandthe/operatordividesthefirstnumberbythesecondnumber.
The%remainderoperatordividesthefirstnumberbythesecondnumberandreturnstheremainderoftheoperation.Thisisusefultodetermineifanumberhasanoddorevenvalue.
The//floordivisionoperatorperformsjustlikethe/divisionoperatorbuttruncatestheresultatthedecimalpoint–removinganyfloatingpointpartfromtheresultingnumber.
The**exponentoperatorreturnstheresultofthefirstnumberraisedtothepowerofthesecondnumber.
Valuesusedwithoperatorstoformexpressionsarecalled“operands”–intheexpression2+3thenumericalvalues2and3aretheoperands.
arithmetic.py
Startanewprogrambycreatingtwovariablescontainingwholenumbers(integers)
a=8
b=2
Next,displaytheresultofaddingthenumbers
print(‘Addition:\t’,a,‘+’,b,‘=’,a+b)
Now,displaytheresultofsubtractingthenumbers
print(‘Subtraction:\t’,a,‘-’,b,‘=’,a-b)
Then,displaytheresultofmultiplyingthenumbers
print(‘Multiplication:\t’,a,‘x’,b,‘=’,a*b)
Displaytheresultofdividingthenumbers,bothwithandwithoutthefloating-pointpartprint(‘Division:\t’,a,‘÷’,b,‘=’,a/b)print(‘FloorDivision:\t’,a,‘÷’,b,‘=’,a//b)
Next,displaytheremainderafterdividingthenumbers
print(‘Remainder:\t’,a,‘%’,b,‘=’,a%b)
Finally,displaytheresultofraisingthefirstnumbertothepowerofthesecondnumberprint(‘Exponent:\t‘,a,‘²=’,a**b,sep=‘’)
Savethenruntheprogramtoseetheresultofthearithmeticaloperations
Here,thespecial\tcharactersequenceaddsaninvisibletabcharactertoformattheoutput.
Youcanusethesepparametertoexplicitlyspecifytheseparationbetweenoutput–here,itspecifiesnospacesbyassigningtwounspacedsinglequotemarks.
AssigningvaluesTheassignmentoperatorcommonlyusedincodingcomputerprogramssimplyusesa=symboltoassignavaluetoavariable.Optionally,thismaybecombinedwithanarithmeticaloperatortoperformarithmeticandassignmentinonesingleoperation.
TheassignmentoperatorsusedtocodePythonprogramsarelistedinthetablebelowtogetherwiththeoperationtheyperform:
Operator: Example: Equivalent:
= a=b a=b
+= a+=b a=(a+b)
-= a-=b a=(a-b)
*= a*=b a=(a*b)
/= a/=b a=(a/b)
%= a%=b a=(a%b)
//= a//=b a=(a//b)
**= a**=b a=(a**b)
Intheexampleabove,variableaisassignedthevaluecontainedinvariableb–sothatbecomesthenewvalueintheavariable.
The+=operatorisusefultoaddavalueontoanexistingvaluestoredintheavariable–makingitacombinedtotalvalue.
Intheexampleabovethe+=operatorfirstaddsthevaluecontainedinvariableatothevaluecontainedinvariableb.Itthenassignstheresulttobecomethenewvaluestoredinvariablea.
Alltheseotheroperatorsworkinthesamewaybymakingthearithmeticaloperationbetweenthetwovaluesfirst,thenassigningtheresultofthatoperationtothefirstvariable–tobecomeitsnewstoredvalue.
Withthe%=operatorthefirstoperandaisdividedbythesecondoperandbthentheremainderisassignedtotheavariable.
Itisimportanttoregardthe=operatortomean“assign”ratherthan“equals”toavoidconfusionwiththe==equalityoperator.
assign.py
Startanewprogrambycreatingtwovariablescontainingintegernumbersanddisplaysbothassignedvaluesa=8
b=4print(‘AssignValues:\t’,’a=’,a,‘\tb=’,b)
Next,addandassignanewvaluetothefirstvariableanddisplayitsstoredvalue
a+=b
print(‘Add&Assign:\t’,’a=’,a,‘\t(8+=4)’)
Now,subtractandassignanewvaluetothefirstvariableanddisplayitsstoredvalue,thenmultiplyandassignavaluetothefirstvariableanddisplayitsstoredvaluea-=bprint(‘Subtract&Assign:\t’,’a=’,a,‘\t(12-4)’)
a*=bprint(‘Multiply&Assign:\t’,’a=’,a,‘\t(8x4)’)
Finally,divideandassignanewvaluetothefirstvariableanddisplayitsstoredvalue,thenremainderandassignavaluetothefirstvariableanddisplayitsstoredvaluea/=b
print(‘Divide&Assign:\t’,’a=’,a,‘\t(32÷4)’)a%=b
print(‘Remainder&Assign:\t’,’a=’,a,‘\t(8%4)’)
Savethenruntheprogramtoseetheresultoftheassignmentoperations
ComparingvaluesTheoperatorsthatarecommonlyusedinPythonprogrammingtocomparetwooperandvaluesarelistedinthetablebelow:
Operator: Comparativetest:
== Equality
!= Inequality
> Greaterthan
< Lessthan
>= Greaterthanorequalto
<= Lessthanorequalto
The==equalityoperatorcomparestwooperandsandwillreturnTrueifbothareequalinvalue,otherwiseitwillreturnaFalsevalue.Ifbotharethesamenumbertheyareequal,orifbotharecharacterstheirASCIIcodevaluesarecomparednumericallytoachievethecomparisonresult.
Conversely,the!=inequalityoperatorreturnsTrueiftwooperandsarenotequal,usingthesamerulesasthe==equalityoperator,otherwiseitreturnsFalse.Equalityandinequalityoperatorsareusefulintestingthestateoftwovariablestoperformconditionalbranchinginaprogramaccordingtotheresult.
The>“greaterthan”operatorcomparestwooperandsandwillreturnTrueifthefirstisgreaterinvaluethanthesecond,oritwillreturnFalseifitisequalorlessinvalue.The<“lessthan”operatormakesthesamecomparisonbutreturnsTrueifthefirstoperandislessinvaluethanthesecond,otherwiseitreturnsFalse.A>“greaterthan”or<“lessthan”operatorisoftenusedtotestthevalueofaniterationcounterinaloop.
Addingthe=operatoraftera>“greaterthan”or<“lessthan”operatormakesitalsoreturnTrueifthetwooperandsareexactlyequalinvalue.
A-ZuppercasecharactershaveASCIIcodevalues65-90anda-zlowercasecharactershaveASCIIcodevalues97-122.
comparison.py
Startanewprogrambyinitializingfivevariableswithvaluesforcomparison
nil=0
num=0top=1
cap=‘A’low=‘a’
Next,addstatementstodisplaytheresultsofnumericandcharacterequalitycomparisonsprint(‘Equality:\t’,nil,‘==’,num,nil==num)
print(‘Equality:\t’,cap,‘==’,low,cap==low)
Now,addastatementtodisplaytheresultofaninequalitycomparison
print(‘Inequality:\t’,nil,‘!=’,top,nil!=top)
Then,addstatementstodisplaytheresultsofgreaterandlessercomparisons
print(‘Greater:\t’,nil,‘>’,top,nil>top)print(‘Lesser:\t’,nil,‘<’,top,nil<top)
Finally,addstatementstodisplaytheresultsofgreaterorequalandlesserorequalcomparisonsprint(‘MoreOrEqual:\t’,nil,‘>=’,num,nil>=num)
print(‘LessorEqual:\t’,top,‘<=’,num,top<=num)
Savethenruntheprogram–toseetheresultofcomparisonoperations
The\tescapesequenceshownhereaddsaninvisibletabcharactertoformattheoutput.
TheASCIIcodevalueforuppercase“A”is65butforlowercase“a”it’s97–sotheircomparisonherereturnsFalse.
FindingtruthThelogicaloperatorsmostcommonlyusedinPythonprogrammingarelistedinthetablebelow:
Operator: Operation:
and LogicalAND
or LogicalOR
not LogicalNOT
ThelogicaloperatorsareusedwithoperandsthathaveBooleanvaluesofTrueorFalse,orarevaluesthatconverttoTrueorFalse.
The(logicalAND)andoperatorwillevaluatetwooperandsandreturnTrueonlyifbothoperandsthemselvesareTrue.OtherwisetheandoperatorwillreturnFalse.Thisisusefulinprogrammingtoperform“conditionalbranching”wherethedirectionofaprogramisdeterminedbytestingtwoconditions–ifbothconditionsaresatisfied,theprogramwillgoinacertaindirection,otherwiseitwilltakeadifferentdirection.
UnliketheandoperatorthatneedsbothoperandstobeTrue,the(logicalOR)oroperatorwillevaluateitstwooperandsandreturnTrueifeitheroneoftheoperandsitselfreturnsTrue.IfneitheroperandreturnsTrue,thentheoroperatorwillreturnFalse.Thisisusefulinprogrammingtoperformacertainactionifeitheroneoftwotestconditionshasbeenmet.
The(logicalNOT)notoperatorisaunaryoperatorthatisusedbeforeasingleoperand.Itreturnstheinversevalueofthegivenoperand,soifthevariableahadavalueofTruethennotawouldhaveavalueofFalse.Thenotoperatorisusefulinprogrammingtotogglethevalueofavariableinsuccessiveloopiterationswithastatementlikea=nota.ThisensuresthatoneachiterationofthelooptheBooleanvalueisreversed,likeflickingalightswitchonandoff.
Theterm“Boolean”referstoasystemoflogicalthoughtdevelopedbytheEnglishmathematicianGeorgeBoole(1815-1864).
logic.py
StartanewprogrambyinitializingtwovariableswithBooleanvaluesforlogicalevaluationa=True
b=False
AddstatementstodisplaytheresultsofANDevaluations
print(‘ANDLogic:’)print(‘aanda=’,aanda)
print(‘aandb=’,aandb)print(‘bandb=’,bandb)
AddstatementstodisplaytheresultsofORevaluations
print(‘\nORLogic:’)
print(‘aora=’,aora)print(‘aorb=’,aorb)
print(‘borb=’,borb)
AddstatementstodisplaytheresultsofNOTevaluations
print(‘\nNOTLogic:’)print(‘a=’,a,‘\tnota=’,nota)
print(‘b=’,b,‘\tnotb=’,notb)
Savethenrunthisprogram–toseetheresultoflogicoperations
InPythonprogramming,BooleanvaluescanalsoberepresentednumericallywhereTrueis1andFalseis0(zero).
NotethattheexpressionFalseandFalsereturnsFalse,notTrue–perhapsdemonstratingthemaxim“twowrongsdon’tmakearight”.
TestingconditionManyprogramminglanguages,suchasC++orJava,havea?:“ternary”operatorthatevaluatesanexpressionforaTrueorFalseconditionthenreturnsoneoftwospecifiedvaluesdependingontheresultoftheevaluation.A?:ternaryoperatorhasthissyntax:(test-expression)?if-true-return-this:if-false-return-this
Unlikeotherprogramminglanguages,Pythondoesnothavea?:
ternaryoperatorbuthasinsteada“conditionalexpression”thatworksinasimilarwayusingifandelsekeywordswiththissyntax:if-true-return-thisif(test-expression)elseif-false-return-this
Althoughtheconditionalexpressionsyntaxcaninitiallyappearconfusingitiswellworthbecomingfamiliarwiththisexpressionasitcanexecutepowerfulprogrambranchingwithminimalcode.Forexample,tobranchwhenavariableisnotavalueofone:if-true-do-thisif(var!=1)elseif-false-do-this
TheconditionalexpressioncanbeusedinPythonprogrammingtoassignthemaximumorminimumvalueoftwovariablestoathirdvariable.Forexample,toassignaminimumlikethis:c=aif(a<b)elseb
TheexpressioninparenthesesreturnsTruewhenthevalueofvariableaislessthanthatofvariableb–sointhiscasethelesservalueofvariableagetsassignedtovariablec.
Similarly,replacingthe<lessthanoperatorinthetestexpressionwiththe>greaterthanoperatorwouldassignthegreatervalueofvariablebtovariablec.
Anothercommonuseoftheconditionalexpressionincorporatesthe%remainderoperatorinthetestexpressiontodetermineifthevalueofavariableisanoddnumberoranevennumber:if-true(odd)-do-thisif(var%2!=0)elseif-false(even)-do-this
Wheretheresultofdividingthevariablevaluebytwodoesleavearemainder,thenumberisodd–wherethereisnoremainderthenumberiseven.Thetestexpression(var%2==1)wouldhavethesameeffectbutitispreferabletotestforinequality–it’seasiertospotwhensomethingisdifferentthanwhenit’sidentical.
Ingeneralprogrammingtermsan“expression”alwaysreturnsavalue,whereasa“statement”neednot–butastatementmayincludeoneormoreexpressions.
Theconditionalexpressionhas,ineffect,threeoperands–thetestexpressionandtwopossiblereturnvalues.
condition.py
Startanewprogrambyinitializingtwovariableswithintegervaluesforconditionalevaluationa=1
b=2
Next,addstatementstodisplaytheresultsofconditionalevaluation–describingthefirstvariable’svalueprint(‘\nVariableaIs:’,‘One’if(a==1)else‘NotOne’)print(‘VariableaIs:’,‘Even’if(a%2==0)else‘Odd’)
Now,addstatementstodisplaytheresultsofconditionalevaluation–describingthesecondvariable’svalueprint(‘\nVariablebIs:’,‘One’if(b==1)else‘NotOne’)
print(‘VariablebIs:’,‘Even’if(b%2==0)else‘Odd’)
Then,addastatementtoassigntheresultofaconditionalevaluationtoanewvariabletop=aif(a>b)elseb
Finally,addastatementtodisplaytheassignedresult–identifyingthegreaterofthetwovariablevaluesprint(‘\nGreaterValueIs:’,top)
Savethenrunthisprogram–toseetheresultofconditionalexpressionoperations
YoumayfindthatsomePythonprogrammersdislikeconditionalexpressionsastheyconsideritssyntaxcontradictstheprincipleofeasyreadability.
SettingorderOperatorprecedencedeterminestheorderinwhichexpressionsgetevaluated.Forexample,intheexpression3*8+4thedefaultorderofprecedencedeterminesthatmultiplicationwiththe*multiplyoperatoriscompletedfirst,sotheresultis28(24+4).
ThetablebelowlistsPython’soperatorprecedenceindescendingorder–thoseonthetoprowhavehighestprecedence,thoseonlowerrowshavesuccessivelylowerprecedence.TheprecedenceofoperatorsonthesamerowischainedLeft-To-Right.
Operator: Description:
** Exponent
+ Positive
- Negative
~ BitwiseNOT
* Multiplication
/ Division
// Floordivision
% Remainder
+ Addition
- Subtraction
| BitwiseOR
^ BitwiseXOR
& BitwiseAND
>> Bitwiserightshift
<< Bitwiseleftshift
>,>=,<,<=,==,!= Comparison
=,%=,/=,//=,-=,+=,*=,**= Assignment
is,isnot Identity
in,notin Membership
not BooleanNOT
and BooleanAND
or BooleanOR
The*multiplyoperatorisonahigherrowthanthe+additionoperator–sointheexpression3*8+4multiplicationiscompletedfirst,beforetheaddition.
Bitwiseoperatorsareusedforlow-levelmanipulationsoareomittedfromthisbook.Identityandmembershipoperatorsareintroducedlaterbutareincludedhereforcompleteness.
order.py
Startanewprogrambyinitializingthreevariableswithintegervaluesforprecedencecomparisona=2
b=4c=8
Next,addstatementstodisplaytheresultsofdefaultprecedenceandforcingadditionbeforemultiplicationprint(‘\nDefaultOrder:\t’,a,‘*’,c,’+’,b,‘=’,a*c+b)
print(‘ForcedOrder:\t’,a,‘*(‘,c,’+’,b,‘)=’,a*(c+b))
Now,addstatementstodisplaytheresultsofdefaultprecedenceandforcingsubtractionbeforedivisionprint(‘\nDefaultOrder:\t’,c,‘//’,b,‘-’,a,‘=’,c//b-a)
print(‘ForcedOrder:\t’,c,‘//(‘,b,’-’,a,‘)=’,c//(b-a))
Finally,addstatementstodisplaytheresultsofdefaultprecedenceandforcingadditionbeforeremainderoperationandbeforeexponentoperationprint(‘\nDefaultOrder:\t’,c,‘%’,a,‘+’,b,‘=’,c%a+b)print(‘ForcedOrder:\t’,c,‘%(‘,a,‘+’,b,‘)=’,c%(a+b))
print(‘\nDefaultOrder:\t’,c,‘**’,a,‘+’,b,‘=’,c**a+b)print(‘ForcedOrder:\t’,c,‘**(‘,a,‘+’,b,‘)=’,c**(a+b))
Savethenrunthisprogram–toseetheresultsofdefaultandexplicitprecedence
The//floordivisionoperatortruncatesfloatingpointvaluesatthedecimalpoint–butthe/divisionoperatorretainsthem.
Donotrelyupondefaultprecedence–alwaysuseparenthesestoclarifyyourexpressions.
Summary• Arithmeticaloperatorscanformexpressionswithtwooperandsforaddition+,
subtraction-,multiplication*,division/,floordivision//,remainder%,orexponent**
• The%remainderoperatorisusefultodeterminewhetheranumberisanoddorevenvalue
• Floordivisionwiththe//operatorremovesanyfloating-pointpartfromtheresult
• Theassignment=operatorcanbecombinedwithanarithmeticaloperatortoperformanarithmeticalcalculationthenassignitsresult
• The+=operatorisusefultoaddavalueontoanexistingvaluestoredinavariabletomakeacombinedtotalvalue
• Comparisonoperatorscanformexpressionscomparingtwooperandsforequality==,inequality!=,greater>,lesser<,greaterorequal>=,andlesserorequal<=values
• LogicalandandoroperatorsformexpressionsevaluatingtwooperandstoreturnaBooleanvalueofTrueorFalse
• ThelogicalnotoperatorreturnstheinverseBooleanvalueofasingleoperand-turningTruetoFalse,andviceversa
• ThenotoperatorisusefultotoggleavaluebetweenTrueandFalseonsuccessiveiterationsofaloop
• Aconditionalif-elseexpressionevaluatesagivenexpressionforaBooleanTrueorFalsevaluethenreturnsoneoftwooperandsdependingonitsresult
• Expressionscontainingmultipleoperatorswillexecutetheiroperationsinaccordancewiththedefaultprecedencerulesunlessexplicitlydeterminedbytheadditionofparentheses()
• Typically,addition+andsubtraction-willbeperformedbeforemultiplication*anddivision/unlessexplicitlyspecified
4Makinglists
Thischapterdemonstrateshowtocreatecodetostoredatainlistsandhowtoretrievedatafromlists.
WritinglistsChanginglistsFixinglistsSettinglistsNamingelementsSummary
WritinglistsSomeprogramminglanguagesallowvariablestobedeclaredwithnoinitialvalue,butinPythonprogrammingavariablemustbeassignedaninitialvalue(initialized)inthestatementthatdeclaresit–otherwisetheinterpreterwillreporta“notdefined”error.
Multiplevariablescanbeinitializedwithacommonvalueinasinglestatementusingasequenceof=assignments.Forexample,tosimultaneouslyassignacommonvaluetothreevariables:a=b=c=10
Alternatively,multiplevariablescanbeinitializedwithdifferingvaluesinasinglestatementusingcommaseparators.Forexample,tosimultaneouslyassigndifferentvaluestothreevariables:a,b,c=1,2,3
Unlikearegularvariable,whichcanonlystoreasingleitemofdata,anarrayvariablecanstoremultipleitemsofdata.InPythontheseareknownas“list”variables.Thedataisstoredsequentiallyinlist“elements”thatareindexnumberedstartingatzero.Sothefirstvalueisstoredinelementzero,thesecondvalueisstoredinelementone,andsoon.Anarraylistiscreatedmuchlikeanyothervariablebutisinitializedbyassigningvaluesasacomma-separatedlistbetweensquarebrackets.Forexample,creatingalistnamed“nums”likethis:nums=[0,1,2,3,4,5]
Asinglelistelementcanbereferencedusingthelistnamefollowedbysquarebracketscontainingthatelement’sindexnumber.Thismeansthatnums[1]referencesthesecondelementintheexampleabove–notthefirstelement.Aselementnumberingstartsatzeroitsfirstelementisreferencedwithnums[0].
Listscanhavemorethanoneindex–torepresentmultipledimensions,ratherthanthesingledimensionofaregularlist.Multi-dimensionallistsofthreeindicesandmoreareuncommonbuttwo-dimensionallistsareusefultostoregrid-basedinformationsuchasX,Ycoordinates.
Alistofstringvaluescanevenbeconsideredtobeamulti-dimensionallistaseachstringisitselfalistofcharacters.Soeachcharactercanbereferencedbyitsindexnumberwithin
itsparticularstring.
list.py
Startanewprogrambyinitializingalistofthreeelementscontainingstringvalues
quarter=[‘January’,‘February’,‘March’]
Next,addstatementstoindividuallydisplaythevaluecontainedineachlistelementprint(‘FirstMonth:’,quarter[0])
print(‘SecondMonth:’,quarter[1])print(‘ThirdMonth:’,quarter[2])
Addastatementtocreateamulti-dimensionallistoftwoelements,whichthemselvesareliststhateachhavethreeelementscontainingintegervaluescoords=[[1,2,3],[4,5,6]]
Now,addstatementstodisplaythevaluescontainedintwospecificinnerlistelementsprint(‘\nTopLeft0,0:’,coords[0][0])
print(‘BottomRight1,2:’,coords[1][2])
Finally,addastatementtodisplayjustonecharacterofastringvalue
print(‘\nSecondMonthFirstLetter:’,quarter[1][0])
Savethenruntheprogram–toseethelistelementvaluesgetdisplayed
Stringindicesmayalsobenegativenumbers–tostartcountingfromtherightwhere-1referencesthelastletter.
Loopstructures,whichareintroducedlaterinthischapter,areoftenusedtoiteratethroughlistelements.
ChanginglistsListvariables,whichcancontainmultipleitemsofdata,arewidelyusedinPythonprogrammingandhavevariousfunction“methods”thatcanbe“dot-suffixed”tothelistnameformanipulation:
ListMethod: Description:
list.append(x) Addsitemxtotheendofthelist
list.extend(L) AddsallitemsinlistLtotheendofthelist
list.insert(i,x) Insertsitemxatindexpositioni
list.remove(x) Removesfirstitemxfromthelist
list.pop(i) Removesitematindexpositioniandreturnsit
list.index(x) Returnstheindexpositioninthelistoffirstitemx
list.count(x) Returnsthenumberoftimesxappearsinthelist
list.sort() Sortalllistitems,inplace
list.reverse() Reversealllistitems,inplace
Forliststhatcontainbothnumericalandstringvaluesthesort()methodreturnsthelistelementssortedfirstnumericallythenalphabetically–forexampleas1,2,3,A,B,C.
Pythonalsohasausefullen(L)functionthatreturnsthelengthofthelistLasthetotalnumberofelementsitcontains.Liketheindex()andcount()methodsthereturnedvalueisnumericsocannotbedirectlyconcatenatedtoatextstringforoutput.
Stringrepresentationofnumericvaluescan,however,beproducedbyPython’sstr(n)functionforconcatenationtootherstrings,whichreturnsastringversionofthenumericnvalue.Similarly,astringrepresentationofanentirelistcanbereturnedbythestr(L)functionforconcatenationtootherstrings.Inbothcasesrememberthattheoriginalversionremainsunchanged,asthereturnedversionsaremerelycopiesoftheoriginal
version.
IndividuallistelementscanbedeletedbyspecifyingthelistnameandindexnumberafterthePythondelkeyword.Thiscanremoveoneelementataspecifiediindexposition,ora“slice”ofelementsusingslicenotationi1:i2tospecifytheindexnumberofthefirstandlastelement.Inthiscase,i1istheindexnumberofthefirstelementtoberemovedandallelementsupto,butnotincluding,theelementatthei2indexnumberwillberemoved.
Pythonalsohasanint(s)functionthatreturnsanumericversionofthestringsvalue.
pop.py
Startanewprogrambyinitializingtwolistsofthreeelementseachcontainingstringvaluesbasket=[‘Apple’,‘Bun’,‘Cola’]
crate=[‘Egg’,‘Fig’,‘Grape’]
Next,addstatementstodisplaythecontentsofthefirstlist’selementsanditslengthprint(‘BasketList:’,basket)print(‘BasketElements:’,len(basket))
Now,addstatementstoaddanelementanddisplayalllistelements,thenremovethefinalelementanddisplayalllistelementsoncemorebasket.append(‘Damson’)
print(‘Appended:’,basket)print(‘LastItemRemoved:’,basket.pop())
print(‘BasketList:’,basket)
Finally,addstatementstoaddallelementsofthesecondlisttothefirstlistanddisplayallthefirstlistelements,thenremoveelementsanddisplaythefirstlistagainbasket.extend(crate)print(‘Extended:’,basket)
delbasket[1]print(‘ItemRemoved:‘,basket)
delbasket[1:3]
print(‘SliceRemoved:’,basket)
Savethenrunthisprogram–toseelistsgetmanipulated
Thelastindexnumberintheslicedenotesatwhatpointtostopremovingelements–buttheelementatthatpositiondoesnotgetremoved.
FixinglistsThevaluesinaregularlistcanbechangedastheprogramproceeds.Eachelementmaybeassignedareplacementvalueusingthe=assignmentoperatortospecifythelistname,elementindexnumber,andthereplacementvalue.Inprogrammingtermsthevaluesstoredinaregularlistare“mutable”–theycanbechanged.Elementscanalsobedynamicallyaddedtoaregularlist,anddynamicallyremovedfromaregularlist,astheprogramproceeds.Thismeansthataregularlistisidealifyourprogramwillmakechangestoelementvalues.
Wherealistwillonlycontainconstantvalues,thatwillneverchangewhentheprogramruns,afixedlistcanbetterbecreated.Inprogrammingterms,thevaluesstoredinafixedlistare“immutable”–theycannotbechanged.Elementscannotbedynamicallyaddedtoafixedlist,ordynamicallyremovedfromafixedlist,astheprogramproceeds.Thismeansthatafixedlistisidealifyourprogramwillnevermakechangestoelementvalues.
Likeindexnumbering,withliststheitemsinatuplesequencearenumberedfromzero.
ArestrictiveimmutablePythonlistisknownasa“tuple”andiscreatedbyassigningvaluesasacomma-separatedlistbetweenparenthesesinaprocessknownas“tuplepacking”:colors_tuple=(‘Red’,‘Green’,‘Red’,‘Blue’,‘Red’)
Anindividualtupleelementcanbereferencedusingthetuplenamefollowedbysquarebracketscontainingthatelement’sindexnumber.Usefully,allvaluesstoredinsideatuplecanbeassignedtoindividualvariablesinaprocessknownas“sequenceunpacking”:a,b,c,d,e=colors_tuple
Regularlistmethods,suchassort()andreverse(),cannotbeusedontuplesbutthebuilt-inPythontype()functioncanbeusedtorevealthedataclasstypeandthebuilt-inlen()functioncanbeusedtoreturnthelengthofthetuple.
Theremustbethesamenumberofvariablesasitemstounpackatuple.
Typically,atupleisusedtostorevaluesthatareacollectionofconstantunchangingvaluessuchasday-of-the-weeknames,month-of-the-yearnames,orpersonaldetailsoffirstname,lastname,date-of-birth,address,phonenumber,etc.
tuple.py
Startanewprogrambyinitializingatuplethendisplayitsclasstype
days=(‘Mon’,‘Tue’,‘Wed’,‘Thu’,‘Fri’,‘Sat’,‘Sun’)
print(‘days:’,type(days))
Next,displaytheentirecontentsofthetuple,itslength,andthevaluestoredinitsfirstelementprint(‘Daysoftheweek:’,days)print(‘No.ofdaysinweek:’,len(days))
print(‘Startdayofweek:’,days[0])
Now,initializeanothertuplecontainingsomepersonaldetailsofauser
user=(‘John’,‘Doe’,‘Paris’,‘555-1234’)
Then,displaytheuser’sfullname
print(‘Name:’,user[0],user[1])
Finally,displaytheuser’sphonenumber
print(‘Phone:’,user[3])
Savethenrunthisprogram–toseethetuplevalues
Atuplemaycontainitemsthatarenotuniquetoitsotherelements.
SettinglistsThevaluesinaregularlistorafixedlisttuplecanberepeatedinitselements,butalistofuniquevaluescanbecreatedwhereduplicationisnotallowed.ArestrictivePythonlistofuniquevaluesisknownasa“set”andiscreatedbyassigningvaluesasacomma-separatedlistbetweencurlybrackets(braces)likethis:phonetic_set={‘Alpha’,‘Bravo’,‘Charlie’}
Asetmaynotcontainitemsthatarenotuniquetoitsotherelements.
Unlikeregularlistsortuples,individualelementsinasetcannotbereferencedusingthesetnamefollowedbysquarebracketscontaininganindexnumber.Instead,setshavepowerfulmethodsthatcanbedot-suffixedtothesetnameformanipulationandcomparisonofvalues:
SetMethod: Description:
set.add(x) Addsitemxtotheset
set.update(x,y,z) Addsmultipleitemstotheset
set.copy() Returnsacopyoftheset
set.pop() Removesonerandomitemfromtheset
set.discard(i) Removesitematpositionifromtheset
set1.intersection(set2) Returnsitemsthatappearinbothsets
set1.difference(set2) Returnsitemsinset1butnotinset2
Thebuilt-inPythontype()functioncanbeusedtorevealthedataclasstypeandthebuilt-inlen()functioncanbeusedtoreturnthelengthoftheset.Additionally,thePythonbuilt-inmembershipoperatorincanbeusedtofindvaluesinaset.
MoresetmethodscanbefoundinthePythondocumentationonlineatdocs.python.orgTypically,asetisusedtostoreuniquevaluesthatareacollectionofchangeablevalues,whichcaneasilybesearchedandcomparedusingthepowerfulsetmethods.Althoughyoucannotaccesssetelementvaluesbyindex,asetcanbeconvertedtoaregularlistusingthePythonbuilt-inlist()functiontoallowelementaccess.
set.py
Startanewprogrambyinitializingasetwithuniquenamevaluesthendisplayitsclasstypeparty_goers={‘Andrew’,‘Barbara’,‘Carole’,‘David’}
print(‘party_goers:’,type(party_goers))
Next,addstatementstosearchthesetelementsfortwospecifiedvalues
print(‘DidDavidgototheparty?’,‘David’inparty_goers)print(‘DidKellygototheparty?’,‘Kelly’inparty_goers)
Now,initializeanothersetwithuniquenamevalues
students={‘Andrew’,‘Kelly’,‘Lynn’,‘David’}
Then,createafurthersetcontainingonlycommonvaluesthatappearinbothprevioussetscommons=party_goers.intersection(students)
Initializearegularlistofthecommonvalues–sotheelementsvaluescanbeindividuallyaccessedparty_students=list(commons)
Finally,displayallcommonvaluesandthevaluestoredinthefirstregularlistelementprint(‘Studentsattheparty:’,party_students)
print(‘Firststudentattheparty:’,party_students[0])
Savethenrunthisprogram–toseethesetvalues
NamingelementsInPythonprogramminga“dictionary”isadatacontainerthatcanstoremultipleitemsofdataasalistofkey:valuepairs.Unlikeregularlistcontainervalues,whicharereferencedbytheirindexnumber,valuesstoredindictionariesarereferencedbytheirassociatedkey.Thekeymustbeuniquewithinthatdictionaryandistypicallyastringname,althoughnumbersmaybeused.
Creatingadictionaryissimplyamatterofassigningthekey:valuepairsasacomma-separatedlistbetweencurlybrackets(braces)toanameofyourchoice.Stringsmustbeenclosedwithinquotes,asusual,anda:coloncharactermustcomebetweenthekeyanditsassociatedvalue.
Inotherprogramminglanguagesalistisoftencalledan“array”andadictionaryisoftencalledan“associativearray”.
Akey:valuepaircanbedeletedfromadictionarybyspecifyingthedictionarynameandthepair’skeytothedelkeyword.Conversely,akey:valuepaircanbeaddedtoadictionarybyassigningavaluetothedictionary’snameandanewkey.
Pythondictionarieshaveakeys()methodthatcanbedot-suffixedtothedictionarynametoreturnalist,inrandomorder,ofallthekeysinthatdictionary.Ifyoupreferthekeystobesortedintoalphanumericorder,simplyenclosethestatementwithintheparenthesesofthePythonsorted()function.
AdictionarycanbesearchedtoseeifitcontainsaparticularkeywiththePythoninoperator,usingthesyntaxkeyindictionary.ThesearchwillreturnaBooleanTruevaluewhenthekeyisfoundinthespecifieddictionary,otherwiseitwillreturnFalse.
DictionariesarethefinaltypeofdatacontaineravailableinPythonprogramming.Insummary,thevarioustypesare:
• Variable–storesasinglevalue
• List–storesmultiplevaluesinanorderedindexarray
• Tuple–storesmultiplefixedvaluesinasequence
• Set–storesmultipleuniquevaluesinanunorderedcollection
• Dictionary–storesmultipleunorderedkey:valuepairs
Dataisfrequentlyassociatedaskey:valuepairs–forexample,whenyousubmitawebformatextvaluetypedintoaninputfieldistypicallyassociatedwiththattextfield’snameasitskey.
dict.py
Startanewprogrambyinitializingadictionarythendisplayitsdataclasstypeanditskey:valuecontentsinfo={‘name’:‘Bob’,‘ref’:‘Python’,‘sys’:‘Win’}
print(‘info:’,type(info))print(‘Dictionary:’,info)
Next,displayasinglevaluereferencedbyitskey
print(‘\nReference:’,info[‘ref’])
Now,displayallkeyswithinthedictionary
print(‘\nKeys:’,info.keys())
Deleteonepairfromthedictionaryandaddareplacementpairthendisplaythenewkey:valuecontentsdelinfo[‘name’]
info[‘user’]=‘Tom’print(‘\nDictionary:’,info)
Finally,searchthedictionaryforaspecifickeyanddisplaytheresultofthesearch
print(‘\nIsThereAnameKey?:’,’name’ininfo)
Savethefilethenrunthisprogram–toseethedictionarykeysandvalues
Noticethatquoteswithinastringmustbeprecededbyabackslashescapecharacter–topreventthestringbeingprematurelyterminated.
Summary• Multiplevariablescanbeinitializedinasinglestatementusingasequenceof=
assignments
• APythonlistisanarrayvariablethatcanstoremultipleitemsofdatainsequentiallynumberedelementsthatstartatzero
• Datastoredinalistelementcanbereferencedusingthelistnamefollowedbyanindexnumberin[]squarebrackets
• Alistelementcanhavemorethanoneindextorepresentmultipledimensions,suchasXandYcoordinates
• Listvariableshaveanumberofmethodsthatcanbedot-suffixedtothelistnameformanipulation
• Thelen()functionreturnsthelengthofaspecifiedlist
• AnindividuallistelementcanbedeletedbyspecifyingthelistnameandelementindexnumbertothePythondelkeyword
• APythontupleisanimmutablelistwhosevaluescanbeassignedtoindividualvariablesby“sequenceunpacking”
• Datastoredinatupleelementcanbereferencedusingthetuplenamefollowedbyanindexnumberin[]squarebrackets
• APythonsetisanorderedcollectionofuniqueelementswhosevaluescanbecomparedandmanipulatedbyitsmethods
• Datastoredinasetcannotbereferencedbyitsindexnumber
• Setvariableshavemethodsthatcanbedot-suffixedtothelistnameformanipulationandcomparison
• ThePythonbuilt-inmembershipinoperatorcanbeusedtoseekavaluewithinaset
• Asetcanbeconvertedtoaregularlistusingthelist()functiontoallowreferenceofelementdatabyindexnumber
• APythondictionaryisalistofkey:valuepairsofdatainwhicheachkeymustbeunique
• Datastoredinadictionaryelementcanbereferencedusingthedictionarynamefollowedbyitskeyin[]squarebrackets
5Controllingblocks
Thischapterdemonstrateshowtocreatecodetocontroltheflowofyourprograms.
BranchingchoicesCountingloopsLoopingconditionsSkippingloopsCatchingerrorsSummary
BranchingchoicesAsinmanyprogramminglanguagesthePythonifkeywordperformsabasicconditionaltestthatevaluatesagivenexpressionforaBooleanvalueofTrueorFalse.Thisallowsaprogramtoproceedindifferentdirectionsaccordingtotheresultofthetestandisknownas“conditionalbranching”.
InPython,thetestedexpressionmustbefollowedbya:colon,thenstatementstoexecutewhenthetestsucceedsshouldfollowbelowonseparatelinesandeachlinemustbeindentedfromtheiftestline.Thesizeoftheindentationisnotimportantbutitmustbethesameforeachline.Sothesyntaxlookslikethis:iftest-expression:
statements-to-execute-when-test-expression-is-Truestatements-to-execute-when-test-expression-is-True
Theif:elif:else:sequenceisthePythonequivalentoftheswitchorcasestatementsfoundinotherlanguages.
Optionally,aniftestcanofferalternativestatementstoexecutewhenthetestfailsbyappendinganelsekeywordafterthestatementstobeexecutedwhenthetestsucceeds.Theelsekeywordmustbefollowedbya:colonandalignedwiththeifkeywordbutitsstatementsmustbeindentedinalikewisemanner,soitssyntaxlookslikethis:iftest-expression:
statements-to-execute-when-test-expression-is-Truestatements-to-execute-when-test-expression-is-True
else:statements-to-execute-when-test-expression-is-Falsestatements-to-execute-when-test-expression-is-False
Aniftestblockcanbefollowedbyanalternativetestusingtheelifkeyword(“elseif”)thatoffersstatementstobeexecutedwhenthealternativetestsucceeds.This,too,mustbealignedwiththeifkeyword,followedbya:colon,anditsstatementsindented.Afinalelsekeywordcanthenbeaddedtoofferalternativestatementstoexecutewhenthetestfails.Thesyntaxforthecompleteif-elif-elsestructurelookslikethis:iftest-expression-1:
statements-to-execute-when-test-expression-1-is-Truestatements-to-execute-when-test-expression-1-is-True
eliftest-expression-2:
statements-to-execute-when-test-expression-2-is-Truestatements-to-execute-when-test-expression-2-is-True
else:
statements-to-execute-when-test-expressions-are-Falsestatements-to-execute-when-test-expressions-are-False
IndentationofcodeisveryimportantinPythonasitidentifiescodeblockstotheinterpreter–otherprogramminglanguagesusebracketingsuchas{}braces.
if.py
Startanewprogrambyinitializingavariablewithuserinputofanintegervalue
num=int(input(‘PleaseEnterANumber:‘))
Next,testthevariableanddisplayanappropriateresponse
ifnum>5:print(‘NumberExceeds5’)
elifnum<5:print(‘NumberisLessThan5’)
else:print(‘NumberIs5’)
Now,testthevariableagainusingtwoexpressionsanddisplayaresponseonlyuponsuccessifnum>7andnum<9:
print(‘Numberis8’)ifnum==1ornum==3:
print(‘NumberIs1or3’)
Savethenruntheprogram–toseeconditionalbranchinginaction
Theuserinputisreadasastringvaluebydefaultsomustbecastasanintdatatypewithint()forarithmeticalcomparison.
TheandkeywordensurestheevaluationisTrueonlywhenbothtestssucceed,whereastheorkeywordensurestheevaluationisTruewheneithertestsucceeds.
CountingloopsAsinotherprogramminglanguages,thePythonforkeywordloopsoverallitemsinanylistspecifiedtotheinkeyword.InPython,thisstatementmustendwitha:coloncharacterandstatementstobeexecutedoneachiterationoftheloopmustbeindented:foreach-iteminlist-name:
statements-to-execute-on-each-iterationstatements-to-execute-on-each-iteration
Becauseastringissimplyalistofcharacters,theforinstatementcanloopovereachcharacter.Similarly,aforinstatementcanloopovereachelementinalist,eachiteminatuple,eachmemberofaset,oreachkeyinadictionary.
TheforloopinPythonisunlikethatinotherlanguagessuchasCasitdoesnotallowstepsizeandendtobespecified.
Aforinloopiteratesovertheitemsofanylistorstringintheorderthattheyappearinthesequencebutyoucannotdirectlyspecifythenumberofiterationstomake,ahaltingcondition,orthesizeofiterationstep.Youcan,however,usethePythonrange()functiontoiterateoverasequenceofnumbersbyspecifyinganumericendvaluewithinitsparentheses.Thiswillgenerateasequencethatstartsatzeroandcontinuesupto,butnotincluding,thespecifiedendvalue.Forexample,range(5)generates0,1,2,3,4.
Optionally,youcanspecifybothastartandendvaluewithintheparenthesesoftherange()function,separatedbyacomma.Forexample,range(1,5)generates1,2,3,4.Also,youcanspecifyastartvalue,endvalue,andastepvaluetotherange()functionasacomma-separatedlistwithinitsparentheses.Forexample,range(1,14,4)generates1,5,9,13.
Youcanspecifythelist’snamewithintheparenthesesofPython’senumerate()functiontodisplayeachelement’sindexnumberanditsassociatedvalue.
Therange()functioncangenerateasequencethatdecreases,countingdown,aswellasthosethatcountupward.
Whenloopingthroughmultiplelistssimultaneously,theelementvaluesofthesameindexnumberineachlistcanbedisplayedtogetherbyspecifyingthelistnamesasacomma-separatedlistwithintheparenthesesofPython’szip()function.
Whenloopingthroughadictionary,youcandisplayeachkeyanditsassociatedvalueusingthedictionaryitems()methodandspecifyingtwocomma-separatedvariablenamestotheforkeyword–oneforthekeynameandtheotherforitsvalue.
for.py
Startanewprogrambyinitializingaregularlist,afixedtuplelist,andanassociativedictionarylistchars=[‘A’,‘B’,‘C’]
fruit=(‘Apple’,‘Banana’,‘Cherry’)info={‘name’:’Mike’,‘ref’:’Python’,‘sys’:’Win’}
Next,addstatementstodisplayalllistelementvalues
print(‘Elements:\t’,end=‘‘)
foriteminchars:print(item,end=‘‘)
Now,addstatementstodisplayalllistelementvaluesandtheirrelativeindexnumberprint(‘\nEnumerated:\t’,end=‘‘)
foriteminenumerate(chars):print(item,end=‘‘)
Then,addstatementstodisplayalllistandtupleelements
print(‘\nZipped:\t’,end=‘‘)
foriteminzip(chars,fruit):print(item,end=‘‘)
Finally,addstatementstodisplayalldictionarykeynamesandassociatedelementvaluesprint(‘\nPaired:’)
forkey,valueininfo.items():print(key,‘=’,value)
Savethenruntheprogram–toseetheitemsdisplayedbytheloopiterations
LoopingconditionsAloopisapieceofcodeinaprogramthatautomaticallyrepeats.Onecompleteexecutionofallstatementswithinaloopiscalledan“iteration”ora“pass”.Thelengthoftheloopiscontrolledbyaconditionaltestmadewithintheloop.WhilethetestedexpressionisfoundtobeTrue,theloopwillcontinue–untilthetestedexpressionisfoundtobeFalse,atwhichpointtheloopends.
InPythonprogramming,thewhilekeywordcreatesaloop.Itisfollowedbythetestexpressionthena:coloncharacter.Statementstoexecutewhenthetestsucceedsfollowbelowonseparatelines,eachlineindentedfromthewhiletestline.Importantly,theloopstatementblockmustincludeastatementthatwillchangetheresultofthetestexpressionevaluation–otherwiseaninfiniteloopiscreated.
UnlikeotherPythonkeywords,thekeywordsTrueandFalsebeginwithuppercaseletters.
IndentationofcodeblocksmustalsobeobservedinPython’sinteractivemode–likethisexamplethatproducesaFibonaccisequenceofnumbersfromawhileloop:
Loopscanbenested,onewithinanother,toallowcompleteexecutionofalliterationsofaninnernestedlooponeachiterationoftheouterloop.A“counter”variablecanbeinitializedwithastartingvalueimmediatelybeforeeachloopdefinition,includedinthetestexpression,andincrementedoneachiterationuntilthetestfails–atwhichpointtheloopends.
TheinteractivePythoninterpreterautomaticallyindentsandwaitswhenitexpectsfurthercodestatementsfromyou.
while.py
Startanewprogrambyinitializinga“counter”variableanddefineanouterloopusingthecountervariableinitstestexpressioni=1
whilei<4:
Next,addindentedstatementstodisplaythecounter’svalueandincrementitsvalueoneachiterationoftheloop
print(‘OuterLoopIteration:’,i)i+=1
Now,(stillindented)initializeasecond“counter”variableanddefineaninnerloopusingthisvariableinitstestexpression
j=1
whilej<4:
Finally,addfurther-indentedstatementstodisplaythiscounter’svalueandincrementitsvalueoneachiteration
print(‘\tInnerLoopIteration:‘,j)j+=1
Savethenrunthisprogram–toseetheoutputdisplayedoneachloopiteration
Theoutputprintedfromtheinnerloopisindentedfromthatoftheouterloopbythe\ttabcharacter.
The+=assignmentstatementi+=1issimplyashorthandwaytosayi=i+1–youcanalsouse*=/=-=shorthandtoassignvaluestovariables.
SkippingloopsThePythonbreakkeywordcanbeusedtoprematurelyterminatealoopwhenaspecifiedconditionismet.Thebreakstatementissituatedinsidetheloopstatementblockandisprecededbyatestexpression.WhenthetestreturnsTrue,theloopendsimmediatelyandtheprogramproceedsontothenexttask.Forexample,inanestedinnerloopitproceedstothenextiterationoftheouterloop.
nest.py
Startanewprogramwithastatementcreatingaloopthatiteratesthreetimes
foriinrange(1,4):
Next,addanindentedstatementcreatinga“nested”innerloopthatalsoiteratesthreetimes
forjinrange(1,4):
Now,addafurther-indentedstatementintheinnerlooptodisplaythecounternumbers(ofboththeouterloopandtheinnerloop)oneachiterationoftheinnerloop
print(‘Runningi=’+i+‘j=’+j)
Savethenrunthisprogram–toseethecountervaluesoneachloopiteration
Comparethesenestedforloopswiththenestedwhileloopsexamplehere.
break.py
Insertabreakstatementatthestartoftheinnerlooptobreakfromthatloop–thenruntheprogramagain
ifi==2andj==1:
print(‘Breaksinnerloopati=2j=1’)break
ThePythoncontinuekeywordcanbeusedtoskipasingleiterationofaloopwhenaspecifiedconditionismet.Thecontinuestatementissituatedinsidetheloopstatementblockandisprecededbyatestexpression.WhenthetestreturnsTrue,thatoneiterationendsandtheprogramproceedstothenextiteration.
Now,insertacontinuestatementatthestartoftheinnerloopblocktoskipthefirstiterationofthatloop–thenruntheprogramoncemore
ifi==1andj==1:
print(‘Continuesinnerloopati=1j=1’)continue
Thebreakstatementhaltsallthreeiterationsoftheinnerloopwhentheouterlooprunsitforthesecondtime.
CatchingerrorsSectionsofaprograminwhichitispossibletoanticipateerrors,suchasthosehandlinguserinput,cantypicallybeenclosedinatryexceptblocktohandle“exceptionerrors”.Thestatementstobeexecutedaregroupedinatry:blockandexceptionsarepassedtotheensuingexcept:blockforhandling.Optionally,thismaybefollowedbyafinally:blockcontainingstatementstobeexecutedafterexceptionshavebeenhandled.
Pythonrecognizesmanybuilt-inexceptionssuchastheNameErrorwhichoccurswhenavariablenameisnotfound,theIndexErrorwhichoccurswhentryingtoaddressanon-existentlistindex,andtheValueErrorwhichoccurswhenabuilt-inoperationorfunctionreceivesaninappropriatevalue.
Eachexceptionreturnsadescriptivemessagethatcanusefullybeassignedtoavariablewiththeaskeyword.Thiscanthenbeusedtodisplaythenatureoftheexceptionwhenitoccurs.
try.py
Startanewprogrambyinitializingavariablewithastringvalue
title=‘CodingforBeginnersInEasySteps’
Next,addatrystatementblockthatattemptstodisplaythevariablevalue–butspecifiesthenameincorrectlytry:
print(titel)
Now,addanexceptstatementblocktodisplayanerrormessagewhenaNameError
occursexceptNameErrorasmsg:
print(msg)
Savethenruntheprogram–toseehowtheerrorgetshandled
Insomeprogramminglanguagesthisstructureisknownastry-catchexceptionhandling.
Multipleexceptionscanbehandledbyspecifiyingtheirtypeasacomma-separatedlistinparentheseswithintheexceptblock:except(NameError,IndexError)asmsg:
print(msg)
Youcanalsocompeltheinterpretertoreportanexceptionbyusingtheraisekeywordtospecifythetypeofexceptiontoberecognizedandacustomdescriptivemessageinparentheses.
raise.py
StartanewPythonscriptbyinitializingavariablewithanintegervalue
day=32
Next,addatrystatementblockthatteststhevariablevaluethenspecifiesanexceptionandcustommessagetry:
ifday>31:
raiseValueError(‘InvalidDayNumber’)#Morestatementstoexecutegetaddedhere.
Now,addanexceptstatementblocktodisplayanerrormessagewhenaValueErroroccursexceptValueErrorasmsg:
print(‘TheProgramfoundAn’,msg)
Then,addafinallystatementblocktodisplayamessageaftertheexceptionhasbeenhandledsuccesfullyfinally:
print(‘ButTodayIsBeautifulAnyway.’)
Savethenruntheprogram–toseetheraisederrorgethandled
Summary• TheifkeywordperformsaconditionaltestonanexpressionforaBooleanvalueofTrue
orFalse
• Conditionalbranchingprovidesalternativestoaniftestwiththeelseandelifkeywords
• Pythontestedexpressionsmustbefollowedbya:coloncharacterandstatementblocksbeindentedfromthetestline
• Aforinloopiteratesovereachiteminaspecifiedlistorstring
• Pythonforinloopstatementsmustbefollowedbya:coloncharacterandstatementblocksbeindentedfromthestatement
• Therange()functiongeneratesanumericalsequencethatcanbeusedtospecifythelengthofaforinloop
• Theenumerate()functioncanspecifythenameofalisttodisplayeachelementindexnumberanditsstoredvalue
• Thezip()functioncandisplaythestoredvaluesofthesameindexnumberinmultiplelists
• AwhilelooprepeatswhileaninitialtestexpressionremainsTrueandendswhenthattestexpressionbecomesFalse
• Pythonwhileloopstatementsmustbefollowedbya:coloncharacterandstatementblocksbeindentedfromthestatement
• Thevalueofacountervariablecanbetestedinatestexpressiontocontrolthenumberofloopiterations
• ThebreakkeywordcanbeusedtotestanexpressionforaTruevalueandimmediatelyexitaloopwhenthetestreturnsFalse
• ThecontinuekeywordcanbeusedtotestanexpressionforaTruevalueandexitasingleiterationwhenthetestreturnsFalse
• Anticipatedruntimeexceptionerrorscanbehandledbyenclosingstatementsinatryexceptblock
• Optionally,afinallystatementcanbeusedtospecifystatementstobeexecutedafterexceptionshavebeenhandled
• Pythontry,except,andfinallystatementsmustbefollowedbya:colonandstatementblocksbeindentedfromthestatement
6Creatingfunctions
Thischapterdemonstrateshowtocodere-usableblocksofcodeinyourprograms.
DefiningblocksAddingparametersReturningresultsStoringfunctionsImportingfunctionsSummary
DefiningblocksPreviousexamplesinthisbookhaveusedbuilt-infunctionsofthePythonprogramminglanguage,suchastheprint()function.However,mostprogramshaveanumberofcoder-definedcustomfunctionsthatcanbecalledasrequiredwhentheprogramruns.
AcustomPythonfunctioniscreatedusingthedef(definition)keywordfollowedbyanameofyourchoiceand()parentheses.Thecodercanchooseanynameforafunctionexceptthekeywordsoftheprogramminglanguageandthenameofanexistingbuilt-infunction.Thislinemustendwitha:coloncharacter,thenthestatementstobeexecutedwheneverthefunctiongetscalledmustappearonlinesbelowandindented.Syntaxofafunctiondefinition,therefore,lookslikethis:deffunction-name():
statements-to-be-executedstatements-to-be-executed
FunctionstatementsmustbeindentedfromthedefinitionlinebythesameamountsothePythoninterpretercanrecognizetheblock.
Oncethefunctionstatementshavebeenexecuted,programflowresumesatthepointdirectlyfollowingthefunctioncall.Thismodularityisveryusefulinprogrammingtoisolatesetroutinessotheycanbecalleduponrepeatedly.
Tocreatecustomfunctionsitisnecessarytounderstandtheaccessibility(“scope”)ofvariablesinaprogram:
• Variablescreatedoutsidefunctionscanbereferencedbystatementsinsidefunctions–theyhave“global”scope
• Variablescreatedinsidefunctionscannotbereferencedfromoutsidethefunctioninwhichtheyhavebeencreated–thesehave“local”scope
Thelimitedaccessibilityoflocalvariablesmeansthatvariablesofthesamenamecanappearindifferentfunctionswithoutconflict.
Avoidusingglobalvariablesinordertopreventaccidentalconflict–useonlylocalvariableswherepossible.
Ifyouwanttocoercealocalvariabletomakeitaccessibleelsewhereitmustfirstbe
declaredwiththePythonglobalkeywordfollowedbyitsnameonly.Itmaysubsequentlybeassignedavaluethatcanbereferencedfromanywhereintheprogram.Whereaglobalvariableandalocalvariablehavethesamename,thefunctionwillusethelocalversion.
def.py
Startanewprogrambyinitalizingaglobalvariable
global_var=1
Next,createafunctionnamed“my_vars”todisplaythevaluecontainedwithintheglobalvariabledefmy_vars():
print(‘Globalvariable:’,global_var)
Now,addindentedstatementstothefunctionblocktoinitializealocalvariableanddisplaythevalueitcontains
local_var=2print(‘Localvariable:’,local_var)
Then,addindentedstatementstothefunctionblocktocreateacoercedglobalvariableandassignaninitialvalue
globalinner_var
inner_var=3
Addastatementafterthefunctiontocalluponthatfunctiontoexecutethestatementsitcontainsmy_vars()
Finally,addastatementtodisplaythevaluecontainedinthecoercedglobalvariableprint(‘CoercedGlobal:’,inner_var)
Savethenruntheprogram–toseethecustomfunctiondisplaythevariablevalues
AddingparametersWhendefiningacustomfunctioninaprogramyoumayoptionallyspecifya“parameter”namebetweenthefunction’sparentheses.An“argument”valuecanthenbepassedtothatparameterbyspecifyingthevalueintheparenthesesofthecalltothefunction.Thefunctioncannowusethatpassedinvalueduringitsexecutionbyreferencingitviatheparametername.Forexample,definingafunctiontoacceptaparametertoprintout:defecho(user):
print(‘User:’,user)
Parametersarespecialvariablesforinternaluseonlywithinafunction–theymustadheretothesamenamingrulesasregularvariables.
Acalltothisfunctionmustspecifyanargumentvaluetobepassedtotheparameterinitsparenthesessoitcanbeprintedout:echo(‘Mike’)
Multipleparameterscanbespecifiedinthefunctiondefinitionbyincludingacomma-separatedlistofparameternameswithinthefunctionparentheses:defecho(user,lang,sys):
print(User:’,user,‘Language:’,lang,‘Platform:’,sys)
Whencallingafunctionwhosedefinitionspecifiesparameters,thecallmustincludethesamenumberofargumentsasparameters.Forexample,tocallthisexamplewithmultipleparameters:echo(‘Mike’,‘Python’,‘Windows’)
Thepassedvaluesmustappearinthesameorderastheparameterlistunlessthecalleralsospecifiestheparameternameslikethis:echo(lang=‘Python’,user=‘Mike’,sys=‘Windows’)
Optionally,adefaultvaluemaybespecifiedintheparameterlistwhendefiningafunction.Thiswillbeoverriddenwhenthecallerspecifiesavalueforthatparameterbutwillbeusedbythefunctionwhennoargumentvaluegetspassedbythecaller:defecho(user,lang,sys=‘Linux’):
print(User:’,user,‘Language:’,lang,‘Platform:’,sys)
Thismeansyoumaycallthefunctionpassingfewervaluesthanthenumberofparametersspecifiedinthefunctiondefinition,tousethedefaultparametervalue,orpassthesamenumberofvaluesasspecifiedparameterstooverridethedefaultvalue.
Nameparametersthesameasvariablespassedtothemtomakethedatamovementobvious.
param.py
Startanewprogrambydefiningafunctionwiththreeparametersthatwillprintoutpassed-inargumentvaluesdefecho(user,lang,sys):
print(‘User:’,user,‘Language:’,lang,‘Platform:’,sys)
Next,callthefunctionpassingstringargumentvaluestothefunctionparametersintheordertheyappearecho(‘Mike’,‘Python’,‘Windows’)
Now,callthefunctionpassingstringargumentstothefunctionparametersbyspecifyingtheparameternamesecho(lang=‘Python’,sys=‘MacOS’,user=‘Anne’)
Then,defineanotherfunctionwithtwoparametershavingdefaultvaluesthatwillprintoutparametervaluesdefmirror(user=‘Carole’,lang=‘Python’):
print(‘\nUser:’,user,‘Language:’,lang)
Finally,addstatementstocallthesecondfunctionbothusingandoverridingdefaultvaluesmirror()
mirror(lang=‘Java’)mirror(user=‘Tony’)
mirror(‘Susan’,‘C++’)
Savethenruntheprogram–toseethefunctiondisplaytheargumentvaluesordefaultparametervalues
ReturningresultsLikePython’sbuilt-instr()function,whichreturnsastringrepresentationofthevaluespecifiedasitsargumentbythecaller,yourcustomfunctionscanalsoreturnavaluetotheircallerbyusingthereturnkeywordtospecifyavaluetobereturned.Forexample,toreturntothecallerthetotalofaddingtwospecifiedparametervalueslikethis:defsum(a,b):
returna+b
Thereturnedresultmaybeassignedtoavariablebythecallerforsubsequentusebytheprogramlikethis:total=sum(8,4)print(‘EightPlusFourIs:’,total)
Orthereturnedresultmaybeuseddirectly“in-line”likethis:print(‘EightPlusFourIs:’,sum(8,4))
Typically,areturnstatementwillappearattheveryendofafunctionblocktoreturnthefinalresultofexecutingallstatementscontainedinthatfunction.
Areturnstatementmay,however,appearearlierinthefunctionblocktohaltexecutionofallsubsequentstatementsinthatblock.Thisimmediatelyresumesexecutionoftheprogramatthecaller.Optionally,thereturnstatementmayspecifyavaluetobereturnedtothecallerorthevaluemaybeomitted.Wherenovalueisspecified,adefaultvalueofNoneisassumed.Typically,thisisusedtohaltexecutionofthefunctionstatementsafteraconditionaltestisfoundtobeFalse.Forexample,whereapassedargumentvalueisbelowaspecifiednumber:defsum(a,b):
ifa<5:return
returna+b
Youcanspecifyadefaultvalueforaparameterinthefunctiondefinition.
Inthiscase,thefunctionwillreturnthedefaultvalueNonewhenthefirstpassedargumentvalueisbelowfiveandthefinalstatementwillnotbeexecuted.
Wherethefunctionistoperformarithmetic,userinputcanbevalidatedforintegervalueswiththebuilt-inisdigit()function.
return.py
Startanewprogrambyinitializingavariablewithuserinputofanintegervalueformanipulationnum=input(‘EnterAnInteger:’)
Next,addafunctiondefinitionthatacceptsasingleargumentvaluetobepassedfromthecallerdefsquare(num):
Now,insertintothefunctionblockanindentedstatementtovalidatethepassedargumentvalueasanintegerorhaltfurtherexecutionofthefunction’sstatements
ifnotnum.isdigit():
return‘InvalidEntry’
Then,addindentedstatementstocastthepassedargumentvalueasanintdatatypethenreturnthesumofsquaringthatvaluetothecaller
num=int(num)returnnum*num
Finally,addastatementtooutputastringandthereturnedvaluefromthefunctioncallprint(num,‘SquaredIs:’,square(num))
Savethenruntheprogram–toseethefunctiondisplaythereturnedvalues
Rememberthatuserinputisreadasastrdatatype–somustbecastintoanint
StoringfunctionsFunctiondefinitionscanusefullybestoredinoneormoreseparatefilesforeasiermaintenanceandtoallowthemtobeusedinseveralprogramswithoutcopyingthedefinitionsintoeachone.EachPythonfilestoringfunctiondefinitionsiscalleda“module”andthemodulenameisthefilenamewithoutthe“.py”extension.
FunctionsstoredinthemodulearemadeavailabletoaprogramusingthePythonimportkeywordfollowedbythemodulename.Althoughnotessential,itiscustomarytoputanyimportstatementsatthebeginningoftheprogram.
Importedfunctionscanbecalledusingtheirnamedotsuffixedafterthemodulename.Forexample,a“steps”functionfromanimportedmodulenamed“ineasy”canbecalledwithineasy.steps().
Wherefunctionsstoredinamoduleincludeparameters,itisoftenusefultoassignadefaultvaluetotheparameterinthedefinition.Thismakesthefunctionmoreversatileasitbecomesoptionalforthecalltospecifyaparametervalue.
cat.py
Startanewmodulebydefiningafunctionthatsuppliesadefaultstringvaluetoitsparameterfordisplaydefpurr(pet=‘ACat’):
print(pet,‘SaysMEOW!’)
Next,addtwomorefunctiondefinitionsthatalsosupplydefaultstringvaluestotheirparametersfordisplaydeflick(pet=‘ACat’):
print(pet,‘DrinksMilk’)
defnap(pet=‘ACat’):print(pet,‘SleepsByTheFire’)
Now,savethefileas“cat.py”sothemoduleisnamed“cat”
Startanewprogramwithastatementtomakethe“cat”modulefunctionsavailable
importcat
kitty.py
Next,calleachfunctionwithoutsupplyinganargument
cat.purr()
cat.lick()cat.nap()
Now,calleachfunctionagainandpassanargumenttoeachthensavethefile
cat.purr(‘Kitty’)
cat.lick(‘Kitty’)cat.nap(‘Kitty’)
Startanotherprogrambymakingthe“cat”modulefunctionsavailableoncemore
importcat
Thenrequesttheuserentersanametooverwritethedefaultparametervalue
pet=input(‘EnterAPetName:‘)
Finally,calleachfunctionpassingtheuser-definedvalueastheargument
cat.purr(pet)
cat.lick(pet)cat.nap(pet)
Savethenruntheseprograms–toseeoutputfromtheimportedmoduleineachprogram
tiger.py
Youcancreateanaliaswhenimportingamoduleusingimportaskeywords.Forexample,importcatastomallowsyoutousetomasthefunctionprefixincalls.
ImportingfunctionsInternally,eachPythonmoduleandprogramhasitsown“symboltable”whichisusedbyallfunctionsdefinedinthatcontextonly.Thisavoidspossibleconflictswithfunctionsofthesamenameinanothermoduleifbothmoduleswereimportedintooneprogram.
Whenyouimportamodulewithanimportstatement,thatmodule’ssymboltabledoesnotgetaddedtotheprogram’ssymboltable–onlythemodule’snamegetsadded.Thatiswhyyouneedtocallthemodule’sfunctionsusingtheirmodulenameprefix.Importinga“steps”functionfromamodulenamed“ineasy”andanother“steps”functionfromamodulenamed“dance”meanstheycanbecalledwithoutconflictasineasy.steps()anddance.steps().
Whereyouimportindividualfunctionnames,themodulenamedoesnotgetimported–soitcannotbeusedasaprefix.
Generally,itispreferabletoavoidconflictsbyimportingthemodulenameandcallingitsfunctionswiththemodulenameprefix,butyoucanimportindividualfunctionnamesinsteadwithafromimportstatement.Themodulenameisspecifiedafterthefromkeyword,andfunctionstoimportarespecifiedasacomma-separatedlistaftertheimportkeyword.Alternatively,the*wildcardcharactercanbespecifiedafterimporttoimportallfunctionnamesintotheprogram’sownsymboltable.Thismeansthefunctionscanbecalledwithoutamodulenameprefix.
dog.py
Startanewmodulebydefiningafunctionthatsuppliesadefaultstringvaluetoitsparameterdefbark(pet=‘ADog’):
print(pet,‘SaysWOOF!’)
Next,addtwomorefunctiondefinitionsthatalsosupplydefaultstringvaluestotheirparametersdeflick(pet=‘ADog’):
print(pet,‘Drinkswater’)
defnap(pet=‘ADog’):print(pet,‘SleepsInTheSun’)
Savethefileas“dog.py”sothemoduleisnamed“dog”
pooch.py
Startanewprogramwithastatementtomakeindividual“dog”modulefunctionsavailablefromdogimportbark,lick,nap
Next,calleachfunctionwithoutsupplyinganargument
bark()
lick()nap()
Now,calleachfunctionagainandpassanargumentvaluetoeachthensavethefile
bark(‘Pooch’)
lick(‘Pooch’)nap(‘Pooch’)
Startanotherprogrambymakingall“dog”modulefunctionsavailable
fromdogimport*
Requestauserentrytooverwritethedefaultparameter
pet=input(‘EnterAPetName:‘)
Finally,calleachfunctionpassingtheuser-definedvalueastheargument
bark(pet)
lick(pet)nap(pet)
Savethenruntheseprograms–toseeoutputfromtheimportedfunctions
Summary• Functionsaredefinedusingthedefkeywordfollowedbyanameofyourchoiceand()
parentheses
• Afunctiondefinitionlinemustendwitha:coloncharacteranditsblockofstatementstoexecutewhenthefunctiongetscalledmustbeindentedbelowthatline
• Variableswithglobalscopecanbereferencedfromanywherewithinthatprogram
• Variableswithlocalscopecanonlybereferencedfromwithinthefunctioninwhichtheyaredeclared
• Alocalvariablecanbecoercedtomakeitgloballyaccessiblebyfirstdeclaringitusingtheglobalkeyword
• Functionparametersarespecialvariablesforuseonlywithinafunction,andargumentsaredatavaluespassedtoparameters
• Parametersaredeclaredasacomma-separatedlistwithintheparenthesesofafunctiondefinition
• Functioncallsmustsupplyargumentdataforeachfunctionparameterunlessadefaultvalueisspecifiedintheirdeclaration
• Datapassedtoparametersinafunctioncallmustappearinthesameorderastheparametersunlesstheirnamesarespecified
• Optionally,thereturnkeywordcanbeusedwithinafunctiontoreturnavaluetothecaller
• Functionscanbestoredinmodulesthatarenamedasthefilenamewithoutthe“.py”fileextension
• Animportstatementmakesmodulefunctionsavailableinaprogrambydot-suffixingtheirnameafterthemodulename
• Internally,eachPythonmodulehasitsownsymboltablesolike-namedfunctionsindifferentmodulesdonotconflict
• Afromimportstatementmakesmodulefunctionsavailableinaprogramwithouttheneedtodot-suffixtheirname
• Animport*statementcanbeusedtoimportamodule’sfunctionsintotheprogram’sownsymboltable
7Sortingalgorithms
Thischapterdemonstrateshowtocodeavarietyofsortingalgorithminstructionsequences.
CopyingsortsSelectingsortsInsertingsortsBubblingsortsMergingsortsPartitioningsortsSummary
CopyingsortsAn“algorithm”isawell-definedsequenceofinstructionstoperformaspecifictask.Eachalgorithmtakesoneormorevaluesasinputandproducesoneormoreresultingvaluesasoutput.
Analgorithmmaybecreatedincodeasafunctionwhosestatementsdefineasequenceofinstructionstoperformthetask.Inputvaluescanbepassedasargumentsinthefunctioncallandresultingvaluescanbereturnedasoutputfromthefunction.Algorithmscanbecoded,usingdatastructuresandcontrolstructuresinavarietyofways,toperformtaskssuchassortinglistsintoorder.
Pythonprovidesthesort()methodforlists(describedhere)butexamplesinthischapterdemonstratehowtocodevarioussortingalgorithmsthatarefoundinmanyprogramminglanguages.
Sortingefficiencymaydependuponthenatureofthelisttobesortedsodifferentalgorithmsmaybebest-suitedtoparticulartasks.Wherethetaskrequiresalisttobesorted,whiletheoriginalunsortedlistremainsintact,analgorithmfunctioncanbepassedareferencetothelistinanargumentasinput.Thefunctioncanthenmakeacopyoftheoriginallist,sortelementsofthatcopyintoorder,thenreturnthesortedcopylistasoutput.Thisalgorithmsimplycopieselementvaluesfromtheoriginallistintoanewlistarraythenarrangestheminascendingvalueorder.
Arraylistelementsarenumberedfromzero.Sohere,element[0]contains5,element[1]contains3,andsoon.
copy.py
Startanewprogrambydeclaringafunctiontoreceivealistreferenceasinputandreturnasortedcopyasoutputdefcopy_sort(array):
copy=array[:]sorted_copy=[]
#Algorithmsequencetobeaddedhere.returnsorted_copy
Next,addtheindentedalgorithmsequencetoinsertthecopiedelementvaluesintotheemptylistinorder
whilelen(copy)>0:
minimum=0forelementinrange(0,len(copy)):
ifcopy[element]<copy[minimum]:minimum=element
print(‘\tRemovingvalue’,copy[minimum],\‘from’,copy)
sorted_copy.append(copy.pop(minimum))
Now,addstatementstocreateanddisplayanunsortedlist
array=[5,3,1,2,6,4]print(‘CopySort…\nArray:’,array)
Finally,addstatementstodisplaytheunsortedlistanditssortedcopythensaveandruntheprogram–toseetheoriginallistremainsintactinunsortedorderprint(‘Copy:’,copy_sort(array))
print(‘Array:’,array)
SelectingsortsOftenyouwillwanttosorttheelementsofanunsortedlistarray“inplace”ratherthansortacopyoftheoriginallist,asdemonstratedinthepreviousexample.Thereareseveralpopularalgorithmsyoucanemploytosortarraysinplace,eachusingadifferenttechniquewiththeirownstrengthsandweaknesses.
A“selectionsort”algorithmexamineseachelementintheunsortedpartofanarraylistandselectstheelementcontainingthelowestvalue.Itthenswapstheselectedelementvaluewiththatcontainedintheelementatthebeginningoftheunsortedpartofthearraylist–therebyincreasingthesizeofthesortedpartofthearrayanddecreasingitsunsortedpart.Thisprocessisrepeateduntilallelementvaluesaresortedintoascendingorder.
Selectionsortisasimpleswap-basedalgorithmthatisrelativelyeasytounderstandandcodeasafunctionalgorithm.Itisoneofthetwomostefficientalgorithmsforsortingsmallarraysof20orsoelements.
Inthisexample,thefinalelementwillalreadycontainthehighestvaluewhenthepenultimateelementhasbeensorted.
selection.py
Startanewprogrambydeclaringafunctiontoreceivealistreferenceasinputandbeginalooptostoreeachelement’svalueandcurrentindexnumberdefselection_sort(array):
forindexinrange(0,len(array)-1):
value=array[index]current=index
#Algorithmsequencetobeaddedhere.
Next,addthealgorithmsequencetorepeatedlyswapthesmallestunsortedvaluewiththefirstunsortedvalue
forelementinrange(index+1,len(array)):ifarray[element]<array[current]:
current=elementarray[index]=array[current]
array[current]=valueprint(‘\tResolvingelement[‘,index,‘]to‘,array)
Now,addstatementstocreateanddisplayanunsortedlist
array=[5,3,1,2,6,4]
print(‘SelectionSort…\nArray:’,array)
Finally,addstatementstocallthealgorithmfunctionanddisplaythelistoncemore–toseethelistsortedinplaceselection_sort(array)print(‘Array:’,array)
Sortinginplaceswapstheelementvaluescontainedintheoriginalreferencedarraylist.
InsertingsortsThetechniqueofswappingelementswithaselectionsortalgorithm,demonstratedinthepreviousexample,workswellbutanalternativetechniquecanbeemployedtosimplyinsertelementsintoanarraylistatthecorrectascendingorderposition.
An“insertionsort”algorithmexaminesthenextelementintheunsortedpartofanarraylistand,ifrequired,insertstheelementatthecorrectascendingorderpositioninthearraylist.Toaccommodatetheinsertedelement,allotherelementsintheunsortedpartofthelistshifttotheright–increasingthesizeofthesortedpartofthearrayanddecreasingitsunsortedpart.Thisprocessisrepeatedforeachelementinturnuntilallelementvaluesaresortedintoascendingorder.
Insertionsortisasimplealgorithmthatisrelativelyeasytounderstandandcodeasafunctionalgorithm.Alongwiththeselectionsortalgorithmitisoneofthetwomostefficientalgorithmsforsortingsmallarraysof20orsoelements.Typically,insertionsortwillrequirefewercomparisonsthanaselectionsortsoisoftenseenasthebestmethodforsortingsmallarrays.
Inthisexample,twostepsareneededtogetthelowestvalueintotheveryfirstelement–as3islessthan5,then1islessthan3.
insertion.py
Startanewprogrambydeclaringafunctiontoreceivealistreferenceasinputandbeginalooptostorethecurrentelement’svaluedefinsertion_sort(array):
forindexinrange(1,len(array)):
value=array[index]#Algorithmsequencetobeaddedhere.
print(‘\tResolvingelement[‘,index,‘]to‘,array)
Next,addthealgorithmsequencetorepeatedlyinsertthecurrentvalueifsmallerthanthatinthecurrentelement
whilearray[index-1]>valueandindex>=1:array[index]=array[index-1]
index-=1array[index]=value
Now,addstatementstocreateanddisplayanunsortedlist
array=[5,3,1,2,6,4]
print(‘InsertionSort…\nArray:’,array)
Finally,addstatementstocallthealgorithmfunctionanddisplaythelistoncemore–toseethelistsortedinplaceinsertion_sort(array)print(‘Array:’,array)
Onsomeiterationsthisalgorithmrecognizesthatelementsinthe“unsorted”partarealreadysortedfollowingearlierinsertions.
BubblingsortsA“bubblesort”algorithmisafurthersimplealternativetotheselectionandinsertionsorttechniques.Thisalgorithmrepeatedlyexamineseachadjacentpairofelementsinanarraylistand,ifrequired,swapsthemaroundtoplacealowervaluebeforeahighervalue–untilallelementsaresortedintoascendingorder.
Bubblesortisasimplealgorithmthatisveryeasytounderstandandcodeasafunctionalgorithm.Althoughthebubblesorttechniqueisgenerallylessefficientthaninsertionsortorselectionsort,itisoneofthequickestalgorithmsfornearly-sortedarrays.
Inthisexample,noswapisneededonthefirstpassforelement[3]and[4]astheirvalues5and6areincorrectorder.
bubble.py
Startanewprogrambydeclaringafunctiontoreceivealistreferenceasinputandbeginanouterlooptorepeatedlyiteratethroughthearraylistdefbubble_sort(array):
forindexinrange(len(array)):#Algorithmsequencetobeaddedhere.
Next,addthealgorithmsequencetoiteratethroughthearraylistelements,upto
thepenultimateelement,andswapvaluesifthenextisgreaterthanthecurrentvalue
forelementinrange(len(array-1)-index):
ifarray[element]>array[element+1]:array[element],array[element+1]=\
array[element+1],array[element]print(‘\tResolvingelement[‘,element,\
‘]to‘,array)
Now,addstatementstocreateanddisplayanunsortedlist
array=[5,3,1,2,6,4]print(‘BubbleSort…\nArray:’,array)
Finally,addstatementstocallthealgorithmfunctionanddisplaythelistoncemore–toseethelistsortedinplacebubble_sort(array)
print(‘Array:’,array)
Inaveragesimplecases,insertionsortoutperformsselectionsort,andselectionsortoutperformsbubblesort.
MergingsortsWhilethesimpleselectionsort,insertionsort,andbubblesorttechniquesworkwellonsmallarraylists,moreefficientcomplexsortingalgorithmsgenerallyworkbetteronlargerarraylists.Typically,thesecomplexsortingalgorithmsemploya“divideandconquer”strategytofirstrepeatedlydividethelistintosub-sections,thenre-assemblethosesub-sectionsinsortedorder.
A“mergesort”algorithmisacomplexsortingalgorithmthatfirstrepeatedlydividesanarrayintoleftandrightsub-sectionsfromthearray’smid-pointuntilitisemptyorhasjustoneelement.Oncethedivisioniscomplete,allsub-sectionsareindividualelements.Thealgorithmthenmergesalltheindividualelementsintoasinglesortedlist.
Mergesortisacomplexalgorithmthatcanbecodedasafunctionalgorithm,whichmakes“recursive”callstorepeatedlydivideanarray.Mergesortisafastalgorithmthatonlycompareselementvalueswhenmergingtheelementsbackintoasortedarraylist.
Inthisexample,thearrayisonlysmallbutthemergesortalgorithmefficientlydividesthenre-assembleslargearraysinexactlythesameway.
Startanewprogrambydeclaringafunctiontoreceivealistreferenceandrepeatedlyiteratethroughanarraylistdefmerge_sort(array):
iflen(array)>1:middle=int(len(array)/2)
left=array[0:middle];right=array[middle:]print(‘\tSplitto’,left,right)
merge_sort(left);merge_sort(right)
#Algorithmsequencetobeaddedhere.
merge.py
Next,addthealgorithmsequencetodividethearraylistelementsintosub-sectionsthenmergethemtogether
i=j=0forelementinrange(len(array)):
L=left[i]ifi<len(left)elseNoneR=right[j]ifj<len(right)elseNone
if((LandR)and(L<R))orRisNone:array[element]=L;i+=1
elif((LandR)and(L>=R))orLisNone:array[element]=R;j+=1
print(‘\t\tMerging’,left,right)
Now,addstatementstocreateanddisplaythearraylist
array=[5,3,1,2,6,4]print(‘MergeSort…\nArray:’,array)
merge_sort(array)print(‘Array:’,array)
Thecodelistedhereusesasemi-colon;separatortowritetwostatementsonsomelines–dueonlytopagelimitations.
PartitioningsortsThetechniqueofdividinganarraylistintosub-sectionsaroundthearray’smid-pointwithamergesortalgorithm,demonstratedinthepreviousexample,workswellbutanalternativetechniquecanbeemployedtopartitionanarraylistarounda“pivot”point.
A“quicksort”algorithmisacomplexsortingalgorithmthatalsoemploysthe“divideandconquer”strategy.Thisfirstspecifiesaparticulararrayelementwhosevaluewillactasthepivot.Thealgorithmthenrepeatedlydividesthearrayintotwo“partitions”–onepartitioncontainingvalueslessthanthepivotandtheotherpartitioncontainingvaluesmorethanthepivot.Oncethepartitionoperationiscomplete,thefinalpivotisinitscorrectpositionsothealgorithmthenmergesthelesserpartitionwiththepivotandthegreaterpartitionintoasinglesortedlist.
Quicksortisacomplexalgorithmthatcanbecodedasafunctionalgorithm,whichmakes“recursive”callstorepeatedlydivideanarray.Quicksortisafastalgorithmthatcompareselementvalueswhendividingtheelementsintopartitions.
Inthisexamplethearrayisonlysmallbutthequicksortalgorithmefficientlypartitionsthenre-assembleslargearraysinexactlythesameway.
Opinionsvaryastowhichelementisbesttochooseasthepivotinthequicksortalgorithm.Somecodersliketochooseamiddleelement,asinthemergesortalgorithminthepreviousexample.Othersprefertochoosethefirstorlastelement,oranelementatsomearbitrarypositioninbetween–liketheexampleopposite.
Startanewprogrambydeclaringafunctiontoreceivealistreferenceandrepeatedlyiteratethroughanarraylistdefquick_sort(array):
iflen(array)>1:pivot=int(len(array)-1)
less=[];more=[]#Algorithmsequencetobeaddedhere.
quick_sort(less);quick_sort(more)
print(‘\tLess:’,less,‘\tPivot:’,array[pivot],\
‘\tMore:’,more)array[:]=less+[array[pivot]]+moreprint(‘\t\t…Merged:’,array)
quick.py
Next,addthealgorithmsequencetodividethearraylistelementsintopartitionsthenmergethemtogether
forelementinrange(len(array)):
value=array[element]ifelement!=pivot:
ifvalue<array[pivot]:less.append(value)
else:more.append(value)
Now,addstatementstocreateanddisplaythearraylist
array=[5,3,1,2,6,4]
print(‘QuickSort…\nArray:’,array)quick_sort(array)
print(‘Array:’,array)
Thequicksortalgorithmuseslessmemorythanmergesortandisoftenconsideredtobethebestsortingalgorithm.
Summary• Analgorithmisawell-definedsequenceofinstructionstoperformaspecifictask
• Eachalgorithmtakesoneormorevaluesasinputandproducesoneormoreresultingvaluesasoutput
• Analgorithmmaybecreatedincodeasafunctionwhosestatementsdefineasequenceofinstructionstoperformatask
• Theefficiencyofsortingalgorithmsmaydependuponthenatureofthelisttobesorted
• Asortingalgorithmfunctioncanmakeacopyofalistpassedasinputandreturnasortedcopyofthatlistasoutput
• Thereareseveralpopularalgorithmstosortarraylistsinplacebuteachhavetheirownstrengthsandweaknesses
• SelectionSortalgorithmsrepeatedlyselectthelowestelementintheunsortedsectionofanarraylistandmoveittotheendofthesortedsectionofthatarray
• InsertionSortalgorithmsrepeatedlytakethenextelementintheunsortedsectionofanarraylistandinsertitintothesortedsectionofthatarrayatthecorrectposition
• BubbleSortalgorithmsrepeatedlycompareadjacentelementsinanunsortedarraylistandswapthemintothecorrectorder
• SelectionSort,InsertionSort,andBubbleSortaresimplecomparisonalgorithmsbutarerelativelyslow
• MergeSortalgorithmsrepeatedlydivideanunsortedarraylistintoleftandrightsub-sectionsfromthearray’smid-pointthenmergethesub-sectionsintoasinglesortedlist
• QuickSortalgorithmsrepeatedlydivideanunsortedarraylistintopartitionscontainingvaluesgreaterorlessthanapivotvaluethenmergethepartitionsintoasinglesortedlist
• MergeSortandQuickSortalgorithmsarefastcomplexalgorithmsthateachemployadivide-and-conquerstrategy
8Importinglibraries
Thischapterdemonstrateshowtocodepre-definedlibraryfunctionalityintoyourprograms.
InspectingPythonDoingmathematicsCalculatingdecimalsTellingtimeRunningtimersSummary
InspectingPythonPythonincludes“sys”and“keyword”modulesthatareusefulforinterrogatingthePythonsystemitself.ThekeywordmodulecontainsalistofallPythonkeywordsinitskwlistattributeandprovidesaniskeyword()functionifyouwanttotestanyword.
Youcanexplorethemanyfeaturesofthe“sys”moduleandindeedanyfeatureofPythonusingtheInteractiveModehelpsystem.Justtypehelp()atthe>>>prompttostarttheHelpsystem,thentypesysatthehelp>promptthatappears.
Perhaps,mostusefully,the“sys”modulehasattributesthatcontainthePythonversionnumber,interpreterlocationonyoursystem,andalistofalldirectorieswheretheinterpreterseeksmodulefiles
–soifyousavemodulefilesinanyofthesedirectoriesyoucanbesuretheinterpreterwillfindthem.
system.py
Startanewprogrambyimportingthe“sys”and“keyword”modulestomaketheirfeaturesavailableimportsys,keywordsystem.py
Next,addastatementtodisplaythePythonversion
print(‘PythonVersion:‘,sys.version)
Now,addastatementtodisplaytheactuallocationonyoursystemofthePythoninterpreterprint(‘PythonInterpreterLocation:‘,sys.executable)
Then,addstatementstodisplayalistofalldirectorieswherethePythoninterpreterlooksformodulefilesprint(‘PythonModuleSearchPath:‘)
forfolderinsys.path:print(folder)
Finally,addstatementstodisplayalistallthePythonkeywords
print(‘PythonKeywords:‘)
forwordinkeyword.kwlist:print(word)
Saveandthenruntheprogram–toseedetailsofthePythonversiononyourownsystem
ThefirstitemonthePythonsearchpathisyourcurrentdirectory–soanyfilewithinthereorwithinanysubdirectoriesyoumaketherewillbefoundbythePythoninterpreter.
SpendalittletimewiththeInteractiveModehelputilitytodiscoverlotsmoreaboutPython.
DoingmathematicsPythonincludesa“math”modulethatprovideslotsoffunctionsyoucanusetoperformmathematicalproceduresonceimported.
Themath.ceil()andmath.floor()functionsenableaprogramtoperformroundingofafloatingpointvaluespecifiedbetweentheirparenthesestotheclosestinteger–math.ceil()roundsupandmath.floor()roundsdownbutthevaluereturned,althoughaninteger,isafloatdatatyperatherthananintdatatype.
Themath.pow()functionrequirestwoargumentstoraiseaspecifiedvaluebyaspecifiedpower.Themath.sqrt()function,ontheotherhand,simplyrequiresasingleargumentandreturnsthesquarerootofthatspecifiedvalue.Bothfunctionresultsarereturnedasanumericvalueofthefloatdatatype.
Integerscanbecastfromtheintdatatypetothefloatdatatypeusingthefloat()functionandtothestringdatatypeusingthestr()function.Typicaltrigonometrycanbeperformedusingfunctionsfromthemathmoduletoo,suchasmath.sin(),math.cosin()andmath.tan().
Additionally,Pythonincludesa“random”modulethatcanbeusedtoproducepseudorandomnumbersonceimportedintoaprogram.
Therandom.random()functionproducesasinglefloating-pointnumberbetweenzeroand1.0.Perhaps,moreinterestingly,therandom.sample()functionproducesalistofelementsselectedatrandomfromasequence.Thismethodrequirestwoargumentstospecifythesequencetoselectfrom,andthelengthofthelisttobeproduced.Astherange()functionreturnsasequenceofnumbers,thiscanbeusedtospecifyasequenceasthefirstargumenttotherandom.sample()function–soitwillrandomlyselectnumbersfromthatsequencetoproducealistinwhichnonumbersrepeat.
maths.py
Startanewprogrambyimportingthe“math”and“random”modulestomaketheirfeaturesavailableimportmath,random
Next,addstatementstodisplaytworoundedvalues
print(‘RoundedUp9.5:‘,math.ceil(9.5))
print(‘RoundedDown9.5:‘,math.floor(9.5))
Now,addastatementtoinitializeavariablewithanintegervalue
num=4
Addstatementstodisplaythesquareandsquarerootofthevariablevalue
print(num,‘Squared:‘,math.pow(num,2))
print(num,‘SquareRoot:‘,math.sqrt(num))
Then,addastatementtoproducearandomlistofsixuniquenumbersbetweenoneand49nums=random.sample(range(1,49),6)
Finally,addastatementtodisplaytherandomlist
print(‘YourLuckyLottoNumbersAre:‘,nums)
Savethenruntheprogram–toseemathresultsandrandomsamples
Allthemathfunctionsherereturnfloating-pointnumbersofthefloatdatatype.
Thelistproducedbyrandom.sample()doesnotactuallyreplaceelementsofthesequencebutmerelycopiesasample,asitsnamesays.
CalculatingdecimalsPythonprogramsthatattemptfloating-pointarithmeticcanproduceunexpectedandinaccurateresultsbecausethefloating-pointnumberscannotaccuratelyrepresentalldecimalnumbers.
inaccurate.py
Startanewprogrambyinitializingtwovariableswithfloating-pointvalues
item=0.70
rate=1.05
Next,initializetwomorevariablesbyattemptingfloating-pointarithmeticwiththefirsttwovariablestax=item*ratetotal=item+tax
Now,addstatementstodisplayvariablevaluesformattedtohavetwodecimalplacessotrailingzerosareshownprint(‘Item:\t’,‘%.2f’%item)print(‘Tax:\t’,‘%.2f’%tax)
print(‘Total:\t’,‘%.2f’%total)
Savethenruntheprogram–toseetheoutputdisplayaninaccurateadditiontotal
expanded.py
Tohelpunderstandthisproblemeditallthreeprintstatementstodisplaythevariablevaluesexpandedto20decimalplaces,thenrunthemodifiedprogramprint(‘Item:\t’,‘%.20f’%item)print(‘Tax:\t’,‘%.20f’%tax)
print(‘Total:\t’,‘%.20f’%total)
Here,thevariablevaluesareformattedusingastringsubstitutiontechniquetoshowtwodecimalplaces–describedinmoredetailhere.
ThisproblemisnotuniquetoPython–JavahasaBigDecimalclassthatovercomesthisprobleminmuchthesamewayasthedecimalmoduleinPython.
Itisnowclearthatthetaxvalueisrepresentednumericallyslightlybelow0.735sogetsroundeddownto0.73.Conversely,thetotalvalueisrepresentednumericallyslightlyabove1.435sogetsroundedupto1.44,creatingtheapparentadditionerror.
Errorsinfloating-pointarithmeticcanbeavoidedusingPython’s“decimal”module.ThisprovidesaDecimal()objectwithwhichfloating-pointnumberscanbemoreaccuratelyrepresented.
decimals.py
Addastatementatthebeginningoftheprogramtoimportthe“decimal”moduletomakeallfeaturesavailablefromdecimalimport*
Next,editthefirsttwovariableassignmenttoobjects
item=Decimal(0.70)
rate=Decimal(1.05)
Savethechangesthenrunthemodifiedprogramtoseebothtaxandtotalrepresentationswillnowgetroundeddown–sotheoutputwillshowaccurateadditionwhenstringformattingischangedbacktotwodecimalplaces
TellingtimeThePython“datetime”modulecanbeimportedintoaprogramtomakeuseoftimesanddates.Itprovidesadatetimeobjectwithattributesofyear,month,day,hour,minute,second,microsecond.
Adatetimeobjecthasatoday()functionthatassignsthecurrentdateandtimevaluestoitsattributesandreturnstheminatuple.Italsohasagetattr()functionthatrequirestwoargumentsspecifyingthedatetimeobjectnameandattributetoretrieve.Alternatively,theattributescanbereferencedusingdotnotationsuchasdatetime.year.
Asthedatetimeobjectisinamoduleofthesamename,simplyimportingthemodulemeansitwouldbereferencedasdatetime.datetime.Usefromdatetimeimport*soitcanbereferencedjustasdatetimealone.Allvaluesinadatetimeobjectarestoredasnumericvaluesbutcanbeusefullytransformedintotextequivalentsusingitsstrftime()function.Thisrequiresasinglestringargumentthatisa“directive”specifyingwhichpartofthetupletoreturnandinwhatformat.Thepossibledirectivesarelistedinthetablebelow:
Directive: Returns:
%A Fullweekdayname(%aforabbreviateddayname)
%B Fullmonthname(%bforabbreviatedmonthname)
%c Dateandtimeappropriateforlocale
%d Dayofthemonthnumber1-31
%f Microsecondnumber0-999999
%H Hournumber0-23(24-hourclock)
%I Hournumber1-12(12-hourclock)
%j Dayoftheyearnumber0-366
%m Monthnumber1-12
%M Minutenumber0-59
%p AMorPMequivalentforlocale
%S Secondnumber0-59
%w Weekdaynumber0(Sunday)-6
%W Weekoftheyearnumber0-53
%X Timeappropriateforlocale(%xforappropriatedate)
%Y Year0001-9999(%yforyear00-99)
%z TimezoneoffsetfromUTCas+HHMMor-HHMM
%Z Timezonename
Asthestrftime()functionrequiresastringargument,thedirectivemustbeenclosedbetweenquotemarks.
time.py
Startanewprogrambyimportingthe“datetime”moduletomakeitsfeaturesavailablefromdatetimeimport*
Next,createadatetimeobjectwithattributesassignedcurrentdateandtimevaluesthendisplayitscontentstoday=datetime.today()
print(‘TodayIs:‘,today)
Addalooptodisplayeachattributevalueindividually
forattrin\[‘year’,‘month’,‘day’,‘hour’,‘minute’,’second’,’microsecond’]:
print(attr,‘:\t’,getattr(today,attr))
Now,addastatementtodisplaytimeusingdotnotation
print(‘Time:‘,today.hour,‘:’,today.minute,sep=‘‘)
Then,assignformatteddayandmonthnamestovariables
day=today.strftime(‘%A’)
month=today.strftime(‘%B’)
Finally,addastatementtodisplaytheformatteddate
print(‘Date:‘,day,month,today.day)
Savethenruntheprogram–toseethedateandtimevaluesgetdisplayed
Noticehowthe\backslashcharacterisusedinthislooptoallowastatementtocontinueonthenextlinewithoutcausinganerror.
Youcanassignnewvaluestoattributesofadatetimeobjectusingitsreplace()function,suchastoday=today.replace(year=2015)
RunningtimersGettingthecurrenttimebothbeforeandafteraneventmeansthatthedurationoftheeventcanbecalculatedbytheirdifference.ThePython“time”modulecanbeimportedintoaprogramtoprovidevarioustime-relatedfunctions.
CurrentsystemtimeisusuallycountedasthenumberofsecondselapsedsincetheEpochat00:00:00GMTonJanuary1,1970.Thetimemodule’stime()functionreturnsthecurrenttimeinsecondssincetheEpochasafloatingpointnumberwhencalled.
Thegmtime()functionconvertselapsedtimefromtheEpochtoastruct_timeobjectatUTCwiththeDaylightSavingTimealwayssettozero,whereaslocaltime()convertstoastruct_timeobjectatyourlocalsystemtime.Thefigurereturnedbythetime()functioncanbeconvertedintoa“struct_time”objectusinggmtime()orlocaltime()functions.Thisobjecthasattributesoftm_year,tm_mon,tm_mday,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_ydayandtm_isdstthatcanbereferencedusingdotnotation.Forexample,struct.tm_wday.
Allvaluesinastruct_timeobjectarestoredasnumericvaluesbutcanbetransformedintotextequivalentsusingthestrftime()function.Thisrequiresanargumentthatisaformat“directive”followedbythenameofthestruct_timeobject.Thepossibledirectivesincludethoselistedinthetablehereforthedatetimeobject.Forexample,strftime(‘%A’,struct)forweekday.
Usefully,thetimemodulealsoprovidesasleep()functionthatcanbeusedtopauseexecutionofaprogram.Itsargumentspecifiestheamountoftimeinsecondsbywhichtodelayexecution.
timer.py
Startanewprogrambyimportingthe“time”moduletomakeitsfeaturesavailable
fromtimeimport*
Next,initializeavariablewithafloatingpointnumberthatisthecurrentelapsedtimesincetheepochstart_timer=time()
Now,addastatementtocreateastruct_timeobjectfromtheelapsedtimevalue
struct=localtime(start_timer)
Then,announcethatacountdowntimerisabouttobeginfromthecurrenttimestartingpointprint(‘StartingCountdownAt:’,strftime(‘%X’,struct))
Addalooptoinitializeandprintacountervariablevaluethendecrementthecounterbyoneandpauseforonesecondoneachiterationi=10
whilei>-1:print(i)
i-=1sleep(1)
Next,initializeavariablewithafloatingpointnumberthatisthecurrentelapsedtimenowsincetheEpochend_timer=time()
Now,initializeavariablewiththeroundedsecondsvalueofthetimedifferencebetweenthetwotimedpointsdifference=round(end_timer-start_timer)
Finally,addastatementtodisplaythetimetakentoexecutethecountdownloop
print(‘\nRuntime:’,difference,‘Seconds’)
Savethenruntheprogram–toseethelooppauseoneachiterationandelapsedtime
Theargumenttothesleep()functionmaybeafloatingpointnumbertoindicateamoreprecisesleeppausetime.
Donotconfusethetime.strftime()functionusedinthisexamplewiththedatetime.strftime()functionusedinthepreviousexample.
Summary• ThesysmodulehasattributesthatcontainthePythonversionnumber,interpreter
location,andpathtosearchformodules
• ThekeywordmodulehasakwlistattributethatcontainsalistofallcurrentPythonkeywords
• Themathmoduleprovidesfunctionstoperformmathematicalproceduressuchasmath.ceil()andmath.floor()
• Themath.pow()andmath.sqrt()functionsbothreturntheirresultsasadecimalvalueofthefloatdatatype
• Trigonometrycanbeperformedusingmathmodulefunctionssuchasmath.sin(),math.cosin()andmath.tan()
• Therandommoduleprovidesarandom()functionthatproducespseudorandomnumbersandasample()functionthatproducesalistofelementsselectedatrandomfromasequence
• Floating-pointfloatnumberscannotaccuratelyrepresentalldecimalnumbers
• ThedecimalmoduleprovidesaDecimal()objectwithwhichfloating-pointnumberscanbeaccuratelyrepresentedtocalculatemonetaryvalues
• Thedatetimemoduleprovidesadatetimeobjectwithyear,month,day,hour,minute,second,microsecondattributesthatcanbereferencedbydot-suffixingorwiththegetattr()function
• Adatetimeobjecthasastrftime()functionthatcanspecifyadirectivetoreturnaformattedpartoftheobject
• Thetimemoduleprovidesatime()functionthatreturnsthecurrentelapsedtimeinsecondssincetheEpoch
• Thegmtime()andlocaltime()functionsreturnastruct_timeobjectwithattributescontainingdateandtimecomponents
9Managingtext
Thischapterdemonstrateshowtomanipulatetextstringsinyourprogramsandhowtostoretextinfiles.
ManipulatingstringsFormattingstringsModifyingstringsAccessingfilesManipulatingcontentUpdatingcontentSummary
ManipulatingstringsStringvaluescanbemanipulatedinaPythonprogramusingthevariousoperatorslistedinthetablebelow:
Operator: Description: Example:
+ Concatenate–joinstringstogether ‘Hello’+‘Mike’
* Repeat–multiplythestring ‘Hello’*2
[] Slice–selectacharacterataspecifiedindexposition ‘Hello’[0]
[:] RangeSlice–selectcharactersinaspecifiedindexrange ‘Hello’[0:4]
in MembershipInclusive–returnTrueifcharacterexistsinthestring ‘H’in‘Hello’
notin MembershipExclusive–returnTrueifcharacterdoesn’texistinstring ‘h’notin‘Hello’
r/R RawString–suppressmeaningofescapecharacters print(r’\n’)
‘‘‘‘‘‘ Docstring–describeamodule,function,class,ormethod defsum(a,b):‘‘‘AddArgs‘‘‘
Themembershipoperatorsperformacase-sensitivematch,so‘A’in‘abc’willfail.
The[]sliceoperatorand[:]rangesliceoperatorrecognizethatastringissimplyalistcontaininganindividualcharacterwithineachlistelement,whichcanbereferencedbytheirindexnumber.
Similarly,theinandnotinmembershipoperatorsiteratethrougheachelementseekingtomatchthespecifiedcharacter.
Therawstringoperatorr(oruppercaseR)mustbeplacedimmediatelybeforetheopeningquotemarktosuppressescapecharactersinthestringandisusefulwhenthestringcontainsthebackslashcharacter.
TheRangeSlicereturnsthestringupto,butnotincluding,thefinalspecifiedindexposition.
A“docstring”isadescriptivestringliteralthatoccursasthefirststatementinamodule,afunction,aclass,oramethoddefinition.Thisshouldbeenclosedwithintriplesinglequotemarks.Uniquely,thedocstringbecomesthe__doc__specialattributeofthatobject,socanbereferencedusingitsnameanddot-suffixing.Allmodulesshouldnormallyhavedocstrings,andallfunctionsandclassesexportedbyamoduleshouldalsohavedocstrings.
manipulate.py
Startanewprogrambydefiningasimplefunctionthatincludesadocstringdescriptiondefdisplay(s):
‘‘’Displayanargumentvalue.’’’print(s)
Next,addastatementtodisplaythefunctiondescription
display(display.doc)
Now,addastatementtodisplayarawstringvaluethatcontainsthebackslashcharacterdisplay(r’C:\ProgramFiles’)
Then,addastatementtodisplayaconcatenationoftwostringvaluesthatincludeanescapecharacterandaspacedisplay(‘\nHello’+‘Python’)
Next,addastatementtodisplayasliceofaspecifiedstringwithinarangeofelementindexnumbersdisplay(‘PythonInEasySteps\n’[7:])
Finally,displaytheresultsofseekingcharacterswithinaspecifiedstring
display(‘P’in‘Python’)
display(‘p’in‘Python’)
Savethenruntheprogram–toseemanipulatedstringsgetdisplayed
Rememberthatstringsmustbeenclosedwithineithersinglequotemarksordoublequotemarks.
Withrangeslice,ifthestartindexnumberisomittedzeroisassumedandiftheendindexnumberisomittedthestringlengthisassumed.
FormattingstringsThePythonbuilt-indir()functioncanbeusefultoexaminethenamesoffunctionsandvariablesdefinedinamodulebyspecifyingthemodulenamewithinitsparentheses.Interactivemodecaneasilybeusedforthispurposebyimportingthemodulenamethencallingthedir()function.Theexamplebelowexaminesthe“dog”modulecreatedhereinChapterSix:
Noticethatthe__doc__attributeintroducedinthepreviousexampleappearslistedherebythedir()function.ThosedefinednamesthatbeginandendwithadoubleunderscorearePythonobjects,whereastheothersareprogrammer-defined.The__builtins__modulecanalsobeexaminedusingthedir()function,torevealthenamesoffunctionsandvariablesdefinedbydefault,suchastheprint()functionandastrobject.
Thestrobjectdefinesseveralusefulfunctionsforstringformatting,includinganactualformat()functionthatperformsreplacements.Astringtobeformattedbytheformat()functioncancontainbothtextand“replacementfields”markingplaceswheretextistobeinsertedfromanorderedcomma-separatedlistofvalues.Eachreplacementfieldisdenotedby{}braces,whichmayoptionallycontaintheindexnumberpositionofthereplacementinthelist.
Donotconfusethestrobjectdescribedherewiththestr()functionthatconvertsvaluestothestringdatatype.
StringsmayalsobeformattedusingtheC-style%ssubstitutionoperatortomarkplacesinastringwheretextistobeinsertedfromacomma-separatedorderedlistofvalues.
format.py
Startanewprogrambyinitializingavariablewithaformattedstring
snack=‘{}and{}’.format(‘Burger’,‘Fries’)
Next,displaythevariablevaluetoseethetextreplacedintheirlistedorder
print(‘\nReplaced:’,snack)
Now,assignadifferentlyformattedstringtothevariable
snack=‘{1}and{0}’.format(‘Burger’,‘Fries’)
Then,displaythevariablevalueagaintoseethetextnowreplacedbytheirspecifiedindexelementvalueprint(‘Replaced:’,snack)
Assignanotherformattedstringtothevariable
snack=‘%sand%s’%(‘Milk’,‘Cookies’)
Finally,displaythevariablevalueoncemoretoseethetextsubstitutedintheirlistedorderprint(‘\nSubstituted:’,snack)
Savethenruntheprogram–toseeformattedstringsgetdisplayed
Youcannotleavespacesaroundtheindexnumberinthereplacementfield.
Otherdatatypescanbesubstitutedusing%dforadecimalinteger,%cforacharacter,and%fforafloating-pointnumber.
ModifyingstringsThePythonstrobjecthasmanyusefulfunctionsthatcanbedot-suffixedtoitsnameformodificationofthestringandtoexamineitscontents.Mostcommonlyusedstringmodificationfunctionsarelistedinthetablebelowtogetherwithabriefdescription:
Method: Description:
capitalize() Changestring’sfirstlettertouppercase
title() Changeallfirstletterstouppercase
upper()lower()swapcase()
Changethecaseofallletterstouppercase,tolowercase,ortotheinverseofthecurrentcaserespectively
join(seq) Mergestringintoseparatorsequenceseq
lstrip()rstrip()strip()
Removeleadingwhitespace,trailingwhitespace,orbothleadingandtrailingwhitespacerespectively
replace(old,new) Replacealloccurrencesofoldwithnew
ljust(w,c)rjust(w,c) Padstringtorightorleftrespectivelytototalcolumnwidthwwithcharacterc
center(w,c) Padstringeachsidetototalcolumnwidthwwithcharacterc(defaultisspace)
count(sub) Returnthenumberofoccurrencesofsub
find(sub) Returntheindexnumberofthefirstoccurrenceofsuborreturn-1ifnotfound
startswith(sub)endswith(sub) ReturnTrueifsubisfoundatstartorendrespectively–otherwisereturnFalse
isalpha()isnumeric()isalnum()
ReturnTrueifallcharactersarelettersonly,arenumbersonly,arelettersornumbersonly–otherwisereturnFalse
islower()isupper()istitle()
ReturnTrueifstringcharactersarelowercase,uppercase,orallfirstlettersareuppercaseonly–otherwisereturnFalse
isspace() ReturnTrueifstringcontainsonlywhitespace–otherwisereturnFalse
isdigit()isdecimal() ReturnTrueifstringcontainsonlydigitsordecimals–otherwisereturnFalse
Aspacecharacterisnotalphanumericsoisalnum()returnsFalsewhenexaminingstringsthatcontainspaces.
modify.py
Startanewprogrambyinitializingavariablewithastringoflowercasecharactersandspacesstring=‘codingforbeginnersineasysteps’
Next,displaythestringcapitalized,titled,andcentered
print(‘\nCapitalized:\t’,string.capitalize())
print(‘\nTitled:\t\t’,string.title())print(‘\nCentered:\t’,string.center(30,‘*’))
Now,displaythestringinalluppercaseandmergedwithasequenceoftwoasterisksprint(‘\nUppercase:\t’,string.upper())
print(‘\nJoined:\t\t’,string.join(‘**’))
Then,displaythestringpaddedwithasterisksontheleft
print(‘\nJustified:\t\t’,string.rjust(30,‘*’))
Finally,displaythestringwithalloccurrencesofthe‘s’
characterreplacedbyasterisksprint(‘\nReplaced:\t’,string.replace(‘s’,‘*’))
Savethenruntheprogram–toseemodifiedstringsgetdisplayed
Withtherjust()functionaRIGHT-justifiedstringgetspaddingaddedtoitsLEFT,andwiththeljust()functionaLEFT-justifiedstringgetspaddingaddedtoitsRIGHT.
AccessingfilesThe__builtins__modulecanbeexaminedusingthedir()functiontorevealthatitcontainsafileobjectthatdefinesseveralmethodsforworkingwithfiles,includingopen(),read(),write(),andclose().
Beforeafilecanbereadorwrittenitfirstlymustalwaysbeopenedusingtheopen()function.Thisrequirestwostringargumentstospecifythenameandlocationofthefile,andoneofthefollowing“mode”specifiersinwhichtoopenthefile:
Filemode: Operation:
r Openanexistingfiletoread
w Openanexistingfiletowrite.Createsanewfileifnoneexistsoropensanexistingfileanddiscardsallitspreviouscontents
a Appendtext.Opensorcreatesatextfileforwritingattheendofthefile
r+ Openatextfiletoreadfromorwriteto
w+ Openatextfiletowritetoorreadfrom
a+ Openorcreatesatextfiletoreadfromorwritetoattheendofthefile
Wherethemodeincludesabafteranyofthefilemodeslistedabove,theoperationrelatestoabinaryfileratherthanatextfile.Forexample,rborw+b
Filemodeparametersarestringvaluessomustbesurroundedbyquotes.
Onceafileisopenedandyouhaveafileobjectandcangetvariousinformationrelatedtothatfilefromitsproperties:
Property: Description:
name Nameoftheopenedfile
mode Modeinwhichthefilewasopened
closed StatusBooleanvalueofTrueorFalse
readable() ReadpermissionBooleanvalueofTrueorFalse
writable() WritepermissionBooleanvalueofTrueorFalse
Youcanalsouseareadlines()functionthatreturnsalistofalllines.
access.py
Startanewprogrambycreatingafileobjectforanewtextfilenamed“example.txt”inwhichtowritecontentfile=open(‘example.txt’,‘w’)
Next,addstatementstodisplaythefilenameandmode
print(‘FileName:’,file.name)
print(‘FileOpenMode:’,file.mode)
Now,addstatementstodisplaythefileaccesspermissions
print(‘Readable:’,file.readable())print(‘Writable:’,file.writable())
Then,defineafunctiontodeterminethefile’sstatus
defget_status(f):
if(f.closed!=False):return‘Closed’
else:return‘Open’
Finally,addstatementstodisplaythecurrentfilestatusthenclosethefileanddisplaythefilestatusoncemoreprint(‘FileStatus:’,get_status(file))
file.close()print(‘\nFileStatus:’,get_status(file))
Savethenruntheprogram–toseeafilegetopenedforwriting,thenseethefilegetclosed
ManipulatingcontentOnceafilehasbeensuccessfullyopeneditcanberead,oraddedto,ornewtextcanbewritteninthefile,dependingonthemodespecifiedinthecalltotheopen()function.Followingthis,theopenfilemustalwaysbeclosedbycallingtheclose()function.
Asyoumightexpect,theread()functionreturnstheentirecontentofthefileandthewrite()functionaddscontenttothefile.
Youcanquicklyandefficientlyreadtheentirecontentsinaloop,iteratinglinebyline.
readwrite.py
Startanewprogrambyinitializingavariablewithaconcatenatedstringcontainingnewlinecharacterspoem=‘Ineversawamanwholooked\n’
poem+=‘Withsuchawistfuleye\n’poem+=‘Uponthatlittletentofblue\n’
poem+=‘Whichprisonerscallthesky\n’
Next,addastatementtocreateafileobjectforanewtextfilenamed“poem.txt”towritecontentintofile=open(‘poem.txt’,‘w’)
Now,addstatementstowritethestringcontainedinthevariableintothetextfile,thenclosethatfilefile.write(poem)file.close()
Then,addastatementtocreateafileobjectfortheexistingtextfile“poem.txt”toreadfromfile=open(‘poem.txt’,‘r’)
Now,addstatementstodisplaythecontentsofthetextfile,thenclosethatfile
forlineinfile:
print(line,end=‘’)file.close()
Savethenruntheprogram–toseethefilecreatedandreadouttodisplay
LaunchtheNotepadtexteditortoconfirmthenewtextfileexistsandrevealitscontentswrittenbytheprogram
Now,addstatementsattheendoftheprogramtoappendacitationtothetextfilethensavethescriptfileagainfile=open(‘poem.txt’,‘a’)
file.write(‘(OscarWilde)’)file.close()
Savethenruntheprogramagaintore-writethetextfilethenviewitscontentsinNotepad–toseethecitationnowappendedaftertheoriginaltextcontent
Writingtoanexistingfilewillautomaticallyoverwriteitscontents!
Suppressthedefaultnewlineprovidedbytheprint()functionwherethestringsthemselvescontainnewlines.
UpdatingcontentAfileobject’sread()functionwill,bydefault,readtheentirecontentsofthefilefromtheverybeginning,atindexpositionzero,totheveryend–attheindexpositionofthefinalcharacter.Optionally,theread()functioncanacceptanintegerargumenttospecifyhowmanycharactersitshouldread.
Thepositionwithinthefile,fromwhichtoreadoratwhichtowrite,canbefinelycontrolledbythefileobject’sseek()function.Thisacceptsanintegerargumentspecifyinghowmanycharacterstomovepositionasanoffsetfromthestartofthefile.
Thecurrentpositionwithinafilecanbediscoveredatanytimebycallingthefileobject’stell()functiontoreturnanintegerlocation.
WhenworkingwithfileobjectsitisgoodpracticetousethePythonwithkeywordtogroupthefileoperationalstatementswithinablock.Thistechniqueensuresthatthefileisproperlyclosedafteroperationsend,evenifanexceptionisraisedontheway,andmuchshorterthanwritingequivalenttryexceptblocks.
update.py
Startanewprogrambyassigningastringvaluetoavariablecontainingtexttobewritteninafiletext=‘Thepoliticalslogan“WorkersOfTheWorldUnite!”\nisfromTheCommunistManifesto.’
Next,addstatementstowritethetextstringintoafileanddisplaythefile’scurrentstatusinthe“with”blockwithopen(‘update.txt’,‘w’)asfile:
file.write(text)print(‘\nFileNowClosed?:’,file.closed)
Now,addanon-indentedstatementafterthe“with”codeblocktodisplaythefile’snewstatusprint(‘FileNowClosed?:’,file.closed)
Then,re-openthefileanddisplayitscontentstoconfirmitnowcontainstheentiretextstringwithopen(‘update.txt’,‘r+’)asfile:
text=file.read()print(‘\nString:’,text)
Next,addindentedstatementstodisplaythecurrentfileposition,thenreposition
anddisplaythatnewpositionprint(‘\nPositionInFileNow:’,file.tell())
position=file.seek(33)print(‘PositionInFileNow:’,file.tell())
Now,addanindentedstatementtooverwritethetextfromthecurrentfileposition
file.write(‘AllLands’)
Then,addindentedstatementstorepositioninthefileoncemoreandoverwritethetextfromthenewposition
file.seek(61)
file.write(‘thetombstoneofKarlMarx.’)
Finally,addindentedstatementstoreturntothestartofthefileanddisplayitsentireupdatedcontents
file.seek(0)text=file.read()
print(‘\nString:’,text)
Savethenruntheprogram–toseethefilestringsgetupdated
Theseek()functionmayoptionallyacceptasecondargumentvalueof0,1,or2tomovethespecifiednumberofcharactersfromthestart,current,orendpositionrespectively–zeroisthedefaultstartposition.
Summary• Stringscanbemanipulatedbyoperatorsforconcatenation+,tojoinstringstogether,
andforrepetition*ofstrings
• Stringscanbemanipulatedbyoperatorsforslice[],andrangeslice[:],thatreferencetheindexnumberofstringcharacters
• Stringscanbemanipulatedbymembershipoperatorsinandnotinthatseektomatchaspecifiedcharacterwithinastring
• Ther(orR)rawstringoperatorcanbeplacedimmediatelybeforeastringtosuppressanyescapecharactersitcontains
• A“docstring”isadescriptivestringwithintriplequotemarksatthestartofamodule,class,orfunction,todefineitspurpose
• The__doc__attributecanbeusedtoreferencethestringdescriptionwithinadocstring
• The__builtins__modulecanbeexaminedusingthedir()functiontorevealthenamesofdefaultfunctionsandvariables
• Astrobjecthasaformat()functionforstringformattingandmanyfunctionsforstringmodification,suchascapitalize()
• Replacementfieldsinastringtobeformattedusingtheformatfunctionaredenotedinacomma-separatedlistby{}braces
• StringscanalsobeformattedusingtheC-style%ssubstitutionoperatortomarkplacesinastringwheretextistobeinserted
• Afileobjecthasopen(),read(),write(),andclose()functionsforworkingwithfiles,andfeaturesthatdescribethefileproperties
• Theopen()functionmustspecifyafilenamestringargumentandafilemodestringparameter,suchas’r’toreadthefile
• Aopenedfileobjecthasinformationpropertiesthatrevealitscurrentstatus,suchasmodeandreadable()values
• Positioninafile,atwhichtoreadorwrite,canbespecifiedwiththeseek()methodandreportedbythetell()function
• ThePythonwithkeywordgroupsfileoperationalstatementswithinablockandautomaticallyclosesanopenfile
10Programmingobjects
Thischapterdemonstrateshowtocodevirtualobjectsintoyourprograms.
DefiningclassesCopyinginstancesAddressingpropertiesDerivingclassesOverridingmethodsApplyingsenseSummary
DefiningclassesThereal-worldobjectsthatsurrounduseachhaveattributesandbehaviorswecandescribe.Forexample,acarmightbedescribedwithacolorattribute“red”andan“acceleration”behavior.Programmingobjectsarelikevirtualrepresentationsofreal-worldobjectsthatdescribeattributesandbehaviorsina“class”structure.
A“class”isaspecifiedprototypedescribingasetofpropertiesthatcharacterizeanobject.Eachclasshasadatastructurethatcancontainbothfunctionsandvariablestocharacterizetheobject.Thepropertiesofaclassarereferredtoasitsdata“members”.Classfunctionmembersareknownasits“methods”,andclassvariablemembers(declaredwithinaclassstructurebutoutsideanymethoddefinitions)areknownasits“attributes”.Classmemberscanbereferencedthroughoutaprogramusingdotnotation,suffixingthemembernameaftertheclassname,withsyntaxofclass-name.method-name()orclass-name.attribute-name.
Aclassdeclarationbeginswiththeclasskeyword,followedbyaprogrammer-specifiedname(adheringtotheusualPythonnamingconventionsbutbeginninginuppercase)thena:colon.Nextcomeindentedstatements,optionallyspecifyingaclassdocumentstring,classvariableattributedeclarations,andclassmethoddefinitions–sotheclassblocksyntaxlookslikethis:classClassName:
‘‘‘class-documentation-string‘‘‘class-variable-declarations
class-method-definitions
Theclassdeclaration,whichspecifiesitsattributesandmethods,isablueprintfromwhichworkingcopies(“instances”)canbemade.Allvariablesdeclaredwithinmethoddefinitionsareknownas“instance”variablesandareonlyavailablelocallywithinthemethodinwhichtheyaredeclared–theycannotbedirectlyreferencedoutsidetheclassstructure.
Itisconventionaltobeginclassnameswithanuppercasecharacterandobjectnameswithlowercase.
Typically,instancevariablescontaindatapassedbythecallerwhenaninstancecopyoftheclassiscreated.Asthisdataisonlyavailablelocallyforinternaluseitiseffectively
hiddenfromtherestoftheprogram.Thistechniqueofdata“encapsulation”ensuresthatdataissecurelystoredwithintheclassstructureandisthefirstprincipleofObjectOrientedProgramming(OOP).
Allpropertiesofaclassarereferencedinternallybythedotnotationprefixself–soanattributenamed“sound”isself.sound.Additionally,allmethoddefinitionsinaclassmusthaveselfastheirfirstparameter–soamethodnamed“talk”istalk(self).
Whenaclassinstanceiscreated,aspecial__init__(self)methodisautomaticallycalled.Subsequentparameterscanbeaddedinitsparenthesesifvaluesaretobepassedtoinitializeitsattributes.
AcompletePythonclassdeclarationcouldlooklikethisexample:classCritter:
‘‘‘Abaseclassforallcritterproperties.‘‘‘count=0
def__init__(self,chat):self.sound=chat
Critter.count+=1deftalk(self):
returnself.sound
Theclassdocumentationstringcanbeaccessedviathespecial__doc__docstringattributewithClassname.__doc__.
Itisusefultoexaminetheclasscomponentsofthisexample:
• Thevariablecountisaclassvariablewhoseintegervaluegetssharedamongallinstancesofthisclass–thisvaluecanbereferencedasCritter.countfrominsideoroutsidetheclass
• Thefirstmethod__init__()istheinitializationmethodthatisautomaticallycalledwhenaninstanceoftheclassiscreated
• The__init__()methodinthiscaseinitializesaninstancevariablesound,withavaluepassedfromthechatparameter,andincrementsthevalueofthecountclassvariablewheneveraninstanceofthisclassiscreated
• Thesecondmethodtalk()isdeclaredlikearegularfunctionexceptthefirstparameterisselfwhichisautomaticallyincorporated–novalueneedstobepassedfromthecaller
• Thetalk()methodinthiscasesimplyreturnsthevalueencapsulatedinthesoundinstancevariable
Whileaprogramclasscannotperfectlyemulateareal-worldobject,theaimistoencapsulateallrelevantattributesandactions.
CopyinginstancesAn“instance”ofaclassobjectissimplyacopyoftheprototypecreatedbycallingthatclassname’sconstructorandspecifyingtherequirednumberofparameterswithinitsparentheses.Thecall’sargumentsmustmatchthosespecifiedbythe__init__()methoddefinition–otherthanavaluefortheinternalselfparameter.
Theclassinstanceobjectreturnedbytheconstructorisassignedtoavariableusingthesyntaxinstance-name=ClassName(args).
Dotnotationcanbeusedtoreferencethemethodsandclassvariableattributesofaninstanceobjectbysuffixingtheirnameasinstance-name.method-name()orinstance-name.attribute-name.
Aconstructorcreatesaclassinstanceusingtheclassnamefollowedbyparenthesescontaininganyrequiredparameters.
Typically,abaseclasscanbedefinedasaPythonmodulefilesoitcanbeimportedintootherscriptswhereinstanceobjectscanbeeasilycreatedfromthe“master”classprototype.
Bird.py
Startanewclassfilebydeclaringanewclasswithadescriptivedocumentstring
classBird:
‘‘’Abaseclasstodefinebirdproperties.’’’
Next,addanindentedstatementtodeclareandinitializeaclassvariableattributewithanintegerzerovalue
count=0
Now,definetheintializerclassmethodtoinitializeaninstancevariableandtoincrementtheclassvariable
def__init__(self,chat):self.sound=chat
Bird.count+=1
Finally,addaclassmethodtoreturnthevalueoftheinstancevariablewhencalled–thensavethisclassfile
deftalk(self):
returnself.sound
YoumustnotpassanargumentvaluefortheselfparameterasthisisautomaticallyincorporatedbyPython.
instance.py
StartaprogrambymakingfeaturesoftheclassfileavailablethendisplayitsdocumentstringfromBirdimport*print(‘\nClassInstancesOf:\n’,Bird.__doc__)
Next,addastatementtocreateaninstanceoftheclassandpassastringargumentvaluetoitsinstancevariablepolly=Bird(‘Squawk,squawk!’)
Now,displaythisinstancevariablevalueandcalltheclassmethodtodisplaythecommonclassvariablevalueprint(‘\nNumberOfBirds:’,polly.count)
print(‘PollySays:’,polly.talk())
Birdinstance–polly
Createasecondinstanceoftheclasspassingadifferentstringargumentvaluetoitsinstancevariableharry=Bird(‘Tweet,tweet!’)
Finally,displaythisinstancevariablevalueandcalltheclassmethodtodisplaythecommonclassvariablevalueprint(‘\nNumberOfBirds:’,harry.count)print(‘HarrySays:’,harry.talk())
Birdinstance–harry
Savebothfilesthenruntheprogram–toseetwoinstancesoftheBirdclassgetcreated
TheclassvariablecountcanalsobereferencedwithBird.countbuttheencapsulatedinstancevariablesoundcanonlybeaccessedbycallinganinstance’stalk()method.
AddressingpropertiesAnattributeofaclassinstancecanbeadded,modified,orremovedatanytimeusingdotnotationtoaddresstheattribute.Makingastatementthatassignsavaluetoanattributewillupdatethevaluecontainedwithinanexistingattributeorcreateanewattributeofthespecifiednamecontainingtheassignedvalue:instance-name.attribute-name=value
delinstance-name.attribute-name
Alternatively,youcanusethefollowingPythonbuilt-infunctionstoadd,modify,orremoveaninstancevariable:
• getattr(instance-name,‘attribute-name‘)–returntheattributevalueoftheclassinstance
• hasattr(instance-name,‘attribute-name‘)–returnTrueiftheattributevalueexistsintheinstance,otherwisereturnFalse
• setattr(instance-name,‘attribute-name‘,value)–updatetheexistingattributevalueorcreateanewattributeintheinstance
• delattr(instance-name,‘attribute-name‘)–removetheattributefromtheinstance
Theattributenamespecifiedtothesebuilt-infunctionsmustbeenclosedwithinquotes.
ThenameofattributesautomaticallysuppliedbyPythonalwaysbeginwithanunderscorecharactertonotionallyindicate“privacy”–sotheseshouldnotbemodified,orremoved.Youcanaddyourownattributesnamedinthiswaytoindicateprivacyifyouwish,butinrealitythesecanbemodifiedlikeanyotherattribute.
address.py
StartanewprogrambymakingfeaturesoftheBirdclassavailablethatwascreatedherefromBirdimport*
Next,createaninstanceoftheclassthenaddanewattributewithanassignedvalueusingdotnotationchick=Bird(‘Cheep,cheep!’)chick.age=‘1week’
Now,displaythevaluesinbothinstancevariableattributes
print(‘\nChickSays:’,chick.talk())
print(‘ChickAge:’,chick.age)
Then,modifythenewattributeusingdotnotationanddisplayitsnewvalue
chick.age=‘2weeks’print(‘ChickNow:’,chick.age)
Next,modifythenewattributeoncemore,thistimeusingabuilt-infunction
setattr(chick,‘age’,‘3weeks’)
Now,displayalistofallnon-privateinstanceattributesandtheirrespectivevaluesusingabuilt-infunctionprint(‘\nChickAttributes…’)
forattribindir(chick):ifattrib[0]!=‘_’:
print(attrib,‘:’,getattr(chick,attrib))
Finally,removethenewattributeandconfirmitsremovalusingabuilt-infunction
delattr(chick,‘age’)print(‘\nChickageAttribute?’,hasattr(chick,‘age’))
Savethenruntheprogram–toseetheinstanceattributesgetaddressed
Birdinstance–chick
Thisloopskipsanyattributewhosenamebeginswithanunderscore,so“private”attributeswillnotgetdisplayedinthelist.
DerivingclassesAPythonclasscanbecreatedasabrandnewclass,likethoseinpreviousexamples,orcanbe“derived”fromanexistingclass.Importantly,aderivedclassinheritsmembersoftheparent(base)classfromwhichitisderived–inadditiontoitsownmembers.
Theabilitytoinheritmembersfromabaseclassallowsderivedclassestobecreatedthatsharecertaincommonproperties,whichhavebeendefinedinthebaseclass.Forexample,a“Polygon”baseclassmaydefinewidthandheightpropertiesthatarecommontoallpolygons.Classesof“Rectangle”andTriangle”couldbederivedfromthePolygonclass–inheritingwidthandheightproperties,inadditiontotheirownmembersdefiningtheiruniquefeatures.
ThevirtueofinheritanceisextremelypowerfulandisthesecondprincipleofObjectOrientedProgramming(OOP).
Aderivedclassdeclarationadds()parenthesesafteritsclassnamespecifyingthenameofitsparentbaseclass.
Polygon.py
CreateanewclassfilethatdeclaresabaseclasswithtwoclassvariablesandamethodtosettheirvaluesclassPolygon:
width=0height=0
defset_values(self,width,height):Polygon.width=width
Polygon.height=height
Rectangle.py
Next,createaclassfilethatdeclaresaderivedclasswithamethodtoreturnmanipulatedclassvariablevaluesfromPolygonimport*
classRectangle(Polygon):defarea(self):
returnself.width*self.height
Triangle.py
Now,createanotherclassfilethatdeclaresaderivedclasswithamethodtoreturnmanipulatedclassvariablevaluesfromPolygonimport*classTriangle(Polygon):
defarea(self):return(self.width*self.height)/2
SavethethreeclassfilesthenstartanewprogrambymakingfeaturesofbothderivedclassesavailablefromRectangleimport*
fromTriangleimport*
Next,createaninstanceofeachderivedclass
rect=Rectangle()trey=Triangle()
Now,calltheclassmethodinheritedfromthebaseclass,passingargumentstoassigntotheclassvariablesrect.set_values(4,5)
trey.set_values(4,5)
Finally,displaytheresultofmanipulatingtheclassvariablesinheritedfromthebaseclassprint(‘RectangleArea:’,rect.area())print(‘TriangleArea:’,trey.area())
Savethenruntheprogram–toseeoutputgetdisplayedusinginheritedfeatures
inherit.py
Aclassdeclarationcanderivefrommorethanoneclassbylistingmultiplebaseclassesintheparenthesesafteritsnameinthedeclaration.
Don’tconfuseclassinstancesandderivedclasses–aninstanceisacopyofaclass,whereasaderivedclassisanewclassthatinheritspropertiesofthebaseclassfromwhichitisderived.
OverridingmethodsAmethodcanbedeclaredinaderivedclasstooverrideamatchingmethodinthebaseclass–ifbothmethoddeclarationshavethesamenameandthesamenumberoflistedparameters.Thiseffectivelyhidesthebaseclassmethodasitbecomesinaccessibleunlessitiscalledexplicitly,usingthebaseclassnameforidentification.
Whereamethodinabaseclasssuppliesadefaultparametervaluethiscanbeusedinanexplicitcalltothebasemethodoralternativevaluescanbesuppliedbyoverridingmethods.
Person.py
CreateanewclassfilethatdeclaresabaseclasswithainitializermethodtosetaninstancevariableandasecondmethodtodisplaythatvariablevalueclassPerson:
‘‘’AbaseclasstodefinePersonproperties.’’’def__init__(self,name):
self.name=namedefspeak(self,msg=‘(CallingTheBaseClass)’):
print(self.name,msg)
Man.py
Next,createaclassfilethatdeclaresaderivedclasswithamethodthatoverridesthesecondbaseclassmethodfromPersonimport*
‘‘’AderivedclasstodefineManproperties.’’’
classMan(Person):defspeak(self,msg):
print(self.name,‘:\n\tHello!’,msg)
Hombre.py
Now,createanotherclassfilethatalsodeclaresaderivedclasswithamethodthatonceagainoverridesthesamemethodinthebaseclassfromPersonimport*
‘‘’AderivedclasstodefineHombreproperties.’’’classHombre(Person):
defspeak(self,msg):print(self.name,‘:\n\tHola!’,msg)
override.py
SavethethreeclassfilesthenstartanewprogrambymakingfeaturesofbothderivedclassesavailablefromManimport*
fromHombreimport*
Next,createaninstanceofeachderivedclass,initializingthe“name”instancevariableattributeguy_1=Man(‘Richard’)guy_2=Hombre(‘Ricardo’)
Now,calltheoverridingmethodsofeachderivedclass,assigningdifferentvaluestothe“msg”parameterguy_1.speak(‘It\’sabeautifulevening.\n’)
guy_2.speak(‘Esunatardehermosa.\n’)
Finally,explicitlycallthebaseclassmethod,passingareferencetoeachderivedclass–butnoneforthe“msg”variablesoitsdefaultvaluewillbeusedPerson.speak(guy_1)Person.speak(guy_2)
Savethenruntheprogram–toseeoutputfromoverridingandbaseclassmethods
Man–Richard
Hombre–Ricardo
Themethoddeclarationinthederivedclassmustexactlymatchthatinthebaseclasstooverrideit.
ApplyingsenseThethreecornerstonesofObjectOrientedProgramming(OOP)areencapsulation,inheritance,andpolymorphism.ExamplesearlierinthischapterhavedemonstratedhowdatacanbeencapsulatedwithinaPythonclass,andhowderivedclassesinheritthepropertiesoftheirbaseclass.Thisexampleintroducesthefinalcornerstoneprincipleofpolymorphism.
Theterm“polymorphism”(fromGreek,meaning“manyforms”)describestheabilitytoassignadifferentmeaning,orpurpose,toanentityaccordingtoitscontext.
InPython,the+characterentitycanbedescribedaspolymorphicbecauseitrepresentseitherthearithmeticaladditionoperator,inthecontextofnumericaloperands,orthestringconcatenationoperatorinthecontextofcharacteroperands.
Perhapsmoreimportantly,PythonclassmethodscanalsobepolymorphicbecausethePythonlanguageuses“ducktyping”–meaning…ifitwalkslikeaduck,swimslikeaduck,andquackslikeaduck,thenthatbirdisreckonedtobeaduck.
Inaduck-typedlanguageyoucancreateafunctiontotakeanobjectofanytypeandcallthatobject’smethods.Iftheobjectdoesindeedhavethecalledmethods(isreckonedtobeaduck)theyareexecuted,otherwisethefunctionsignalsarun-timeerror.
Like-namedmethodsofmultipleclassescanbecreatedandinstancesofthoseclasseswillexecutetheassociatedversion.
Duck.py
CreateanewclassfilethatdeclaresaclasswithmethodstodisplaystringsuniquetotheclassclassDuck:
deftalk(self):print(‘\nDuckSays:Quack!’)
defcoat(self):print(‘DuckWears:Feathers’)
Mouse.py
Next,createaclassfilethatdeclaresaclasswithlike-namedmethodsbuttodisplaystringsuniquetothisclassclassMouse:
deftalk(self):print(‘\nMouseSays:Squeak!’)
defcoat(self):print(‘MouseWears:Fur’)
polymorph.py
SavethetwoclassfilesthenstartanewprogrambymakingfeaturesofbothclassesavailablefromDuckimport*
fromMouseimport*
Next,defineafunctionthatacceptsanysingleobjectasitsparameterandattemptstocallmethodsofthatobjectdefdescribe(object):
object.talk()
object.coat()
Now,createaninstanceobjectofeachclass
donald=Duck()mickey=Mouse()
Finally,addstatementstocallthefunctionandpasseachinstanceobjecttoitasanargumentdescribe(donald)
describe(mickey)
Savethenruntheprogram–toseethemethodsoftheassociatedversionsgetcalled
Duck–donald
Mouse–mickey
Aclasscanhaveonlyonemethodwithagivenname–methodoverloadingisnotsupportedinPython.
ObjectOrientedProgrammingwithPythonallowsdataencapsulation,inheritance,andpolymorphism.Baseclassmethodscanbeoverriddenbylike-namedmethodsinderivedclasses.Pythondoesnot,however,supportthetechniqueof“overloading”foundinotherlanguages–inwhichmethodsofthesamenamecanbecreatedwithdifferentparameterlistsinasingleclass.
Summary• Programmingobjectsarelikevirtualrepresentationsofreal-worldobjectsdescribing
attributesandbehaviorsina“class”
• Aclassisadatastructureprototypedescribingobjectpropertieswithitsmethodsandattributemembers
• Eachclassdeclarationbeginswiththeclasskeywordandisfollowedbyanindentedcodeblockthatmaycontainaclassdocumentstring,classvariables,andclassmethods
• Classvariableshaveglobalscopebutinstancevariables(declaredwithinmethoddefinitions)haveonlylocalscope
• Instancevariablesencapsulatedatasecurelyinaclassstructureandareinitializedwhenaclassinstanceiscreated
• Propertiesofaclassarereferencedbydotnotationandareaddressedinternallyusingtheselfprefix
• Aclassinstanceisacopyoftheprototypethatautomaticallycallsits__init__()methodwhentheinstanceisfirstcreated
• Anattributeofaclasscanbeadded,modified,orremovedusingdotnotationormanipulatedusingthebuilt-infunctionsgetattr(),hasattr(),setattr(),anddelattr()
• ThenameofattributesautomaticallysuppliedbyPythonbeginwithanunderscorecharactertonotionallyindicateprivacy
• Aderivedclassinheritsthemethodandattributemembersoftheparentbaseclassfromwhichitisderived
• Thedeclarationofaderivedclassmuststatethenameofitsparentbaseclassinparenthesesafteritsownclassname
• Amethodofaderivedclasscanoverrideamatchingmethodofthesamenameinitsparentbaseclass
• Amethodofabaseclasscanbecalledexplicitlyusingthebaseclassnameforidentification
• Pythonisaduck-typedlanguagethatsupportspolymorphismforlike-namedmethodsofmultipleclasses
• ThethreecornerstonesofObjectOrientedProgramming(OOP)areEncapsulation,Inheritance,andPolymorphism
11Buildinginterfaces
Thischapterdemonstrateshowtocodegraphicalwindowedprograms.
LaunchinginterfacesRespondingbuttonsDisplayingmessagesGatheringentriesListingoptionsPollingradiosCheckingboxesAddingimagesSummary
LaunchinginterfacesThestandardPythonmodulethatyoucanusetocreategraphicalapplicationsiscalled“tkinter”–atoolkittointerfacewiththesystemGUI(GraphicalUserInterface).
Thetkintermodulecanbeimportedintoaprogramlikeanyothermoduletoprovideattributesandmethodsforwindowedapps.EverytkinterprogrammustbeginbycallingtheTk()constructortocreateawindowobject.Thewindow’ssizecanoptionallybespecifiedasa‘widthxheight’stringargumenttothewindowobject’sgeometry()method.Similarly,thewindow’stitlecanbespecifiedasa‘title’stringargumenttothewindowobject’stitle()method.Ifnotspecifieddefaultsizeandtitlevalueswillbeused.
TherecanbeonlyonecalltotheTk()constructoranditmustbeatthestartoftheprogramcode.
Everytkinterprogrammustalsocallthewindowobject’smainloop()methodtocaptureevents,suchaswhentheuserclosesthewindowtoquittheprogram.Thisloopshouldappearattheendoftheprogramasitalsohandleswindowupdatesthatmaybeimplementedduringexecution.
Withtkinter,allthegraphicalcontrolsthatcanbeincludedintheapplicationwindow,suchasbuttonsorcheckboxes,arereferredtoas“widgets”.Perhapsthesimplestwidgetisanon-interactivelabelobjectthatmerelydisplaystextoranimageintheappinterface.Alabelobjectcanbecreatedbyspecifyingthewindowobject’snameandtext=’string’asargumentstoaLabel()constructor.
Oncecreated,eachwidget,suchasalabel,mustthenbeaddedtothewindowusingoneofthese“geometrymanager”methods:
• pack()–placesthewidgetagainstaspecifiedsideofthewindowusingTOP,BOTTOM,LEFT,orRIGHTconstantvaluesspecifiedtoitsside=argument
• place()–placesthewidgetatXYcoordinatesinthewindowusingnumericalvaluesspecifiedtoitsx=andy=arguments
• grid()–placesthewidgetinacellwithinthewindowusingnumericalvaluesspecifiedtorow=andcolumn=arguments
Thegrid()geometrymanagermethodisdemonstratedintheexamplehere.
Optionally,thepack()methodmayincludeafillargumenttoexpandthewidgetinavailable
space.Forexample,withfill=‘x’.Alternatively,thepack()methodmayincludepadxandpadyargumentstoexpandthewidgetalonganaxisaspecifiedamount.
window.py
Startanewprogramwithastatementtomakethe“tkinter”moduleGUImethodsandattributesavailablefromtkinterimport*
Next,addastatementtocalluponaconstructortocreateawindowobject
window=Tk()
Now,addastatementtospecifyatitleforthiswindow
window.title(‘LabelExample’)
Then,addastatementtocalluponaconstructortocreatealabelobject
label=Label(window,text=‘HelloWorld!’)
Usethepackertoaddthelabeltothewindowwithbothhorizontalandverticalpaddingforpositioninglabel.pack(padx=200,pady=50)
Finally,addthemandatorystatementtomaintainthewindowbycapturingevents
window.mainloop()
Savethenruntheprogram–toseeawindowappearcontainingalabelwidget
Widgetswillnotappearinthewindowwhenrunningtheprogramunlesstheyhavebeenaddedwithageometrymanager.
RespondingbuttonsAButtonwidgetprovidesagraphicalbuttoninanapplicationwindowthatmaycontaineithertextoranimagetoconveythebutton’spurpose.AbuttonobjectiscreatedbyspecifyingthewindownameandoptionsasargumentstoaButton()constructor.Eachoptionisspecifiedasanoption=valuepair.Thecommandoptionmustalwaysspecifythenameofafunctionormethodtocallwhentheuserclicksthatbutton.Themostpopularoptionsarelistedbelowtogetherwithabriefdescription:
Option: Description:
activebackground Backgroundcolorwhenthecursorisover
activeforeground Foregroundcolorwhenthecursorisover
bd Borderwidthinpixels(defaultis2)
bg Backgroundcolor
command Functiontocallwhenclicked
fg Foregroundcolor
font Fontforbuttonlabel
height Buttonheightintextlines,orpixelsforimages
highlightcolor Bordercolorwheninfocus
image Imagetobedisplayedinsteadoftext
justify MultipletextlinesasLEFT,CENTER,orRIGHT
padx Horizontalpadding
pady Verticalpadding
relief BorderstyleofSUNKEN,RIDGE,RAISEDorGROOVE
state EnabledstatusofNORMALorDISABLED
underline Indexnumberintextofcharactertounderline
width Buttonwidthinletters,orpixelsforimages
wraplength Lengthatwhichtowraptext
Youcanalsocallabutton’sinvoke()methodto,inturn,callthefunctionnominatedtoitscommandoption.Thevaluesassignedtootheroptionsdeterminethewidget’sappearance.Thesecanbealteredbyspecifyinganewoption=valuepairasanargumenttothewidget’sconfigure()method.Additionally,acurrentoptionvaluecanberetrievedbyspecifyingitsnameasastringargumenttothewidget’scget()method.
button.py
StartanewprogrambymakingGUIfeaturesavailablethencreateawindowandspecifyatitlefromtkinterimport*
window=Tk()window.title(‘ButtonExample’)
Next,createabuttontoexittheprogramwhenclicked
btn_end=Button(window,text=‘Close’,command=exit)
Now,addafunctiontotogglethewindow’sbackgroundcolorwhenanotherbuttongetsclickeddeftog():
ifwindow.cget(‘bg’)==‘yellow’:window.configure(bg=‘gray’)
else:window.configure(bg=‘yellow’)
Then,createabuttontocallthefunctionwhenclicked
btn_tog=Button(window,text=‘Switch’,command=tog)
Addthebuttonstothewindowwithpositionalpadding
btn_end.pack(padx=150,pady=20)
btn_tog.pack(padx=150,pady=20)
Finally,addthelooptocapturethiswindow’sevents
window.mainloop()
Savethenruntheprogramandclickthebutton–toseethewindow’sbackgroundcolorchange
Onlythefunctionnameisspecifiedtothecommandoption.Donotaddtrailingparenthesesintheassignment.
The‘gray’coloristheoriginaldefaultcolorofthewindow.
DisplayingmessagesAprogramcandisplaymessagestotheuserbycallingmethodsprovidedinthe“tkinter.messagebox”module.Thismustbeimportedseparatelyanditslengthynamecanusefullybeassignedashortaliasbyanimportasstatement.
Amessageboxiscreatedbysupplyingaboxtitleandthemessagetobedisplayedasthetwoargumentstooneofthesemethods:
Method: Icon: Buttons:
showinfo() OK
showwarning() OK
showerror() OK
askquestion() Yes(returnsthestring‘yes’)andNo(returnsthestring‘no’)
askokcancel() OK(returns1)andCancel
askyesno() Yes(returns1)andNo
askretrycancel() Retry(returns1)andCancel
Onlytheaskquestion()methodreturnstwovalues–theaskyesno()NobuttonandbothCancelbuttonsreturnnothing.
ThosemethodsthatproduceamessageboxcontainingasingleOKbuttonreturnnovaluewhenthebuttongetsclickedbytheuser.Thosethatdoreturnavaluecanbeusedtoperformconditionalbranchingbytestingthatvalue.
message.py
StartanewprogrambymakingGUIfeaturesavailableandmessageboxfeaturesavailableasashortaliasfromtkinterimport*
importtkinter.messageboxasbox
Next,createawindowobjectandspecifyatitle
window=Tk()window.title(‘MessageBoxExample’)
Addafunctiontodisplayvariousmessageboxes
defdialog():
var=box.askyesno(‘MessageBox’,‘Proceed?’)ifvar==1:
box.showinfo(‘YesBox’,‘Proceeding…’)else:
box.showwarning(‘NoBox’,‘Canceling…’)
Then,createabuttontocallthefunctionwhenclicked
btn=Button(window,text=‘Click’,command=dialog)
Addthebuttontothewindowwithpositionalpadding
btn.pack(padx=150,pady=50)
Finally,addthelooptocapturethiswindow’sevents
window.mainloop()
Savethefilethenruntheprogramandclickthebutton–toseethemessageboxesappear
Optionscanbeaddedasathirdargumenttothesemethodcalls.Forexample,addtype=’abortretryignore’togetthreebuttons.
GatheringentriesAnEntrywidgetprovidesasingle-lineinputfieldinanapplicationwheretheprogramcangatherentriesfromtheuser.Anentryobjectiscreatedbyspecifyingthenameofitsparentcontainer,suchasawindoworframename,andoptionsasargumentstoanEntry()constructor.Eachoptionisspecifiedasanoption=valuepair.Popularoptionsarelistedbelowtogetherwithabriefdescription:
Option: Description:
bd Borderwidthinpixels(defaultis2)
bg Backgroundcolor
fg Foregroundcolorusedtorenderthetext
font Fontforthetext
highlightcolor Bordercolorwheninfocus
selectbackground Backgroundcolorofselectedtext
selectforeground Foregroundcolorofselectedtext
show Hidepasswordcharacterswithshow=’*’
state EnabledstatusofNORMALorDISABLED
width Entrywidthinletters
Multiplewidgetscanbegroupedinframesforbetterpositioning.AframeobjectiscreatedbyspecifyingthenameofthewindowtoaFrame()constructor.Theframe’snamecanthenbespecifiedasthefirstargumenttothewidgetconstructorstoidentifyitasthatwidget’scontainer.
Whenactuallyaddingwidgetstotheframe,youcanspecifywhichsidetopackthemtointheframewithTOP,BOTTOM,LEFT,orRIGHTconstants.Forexample,entry.pack(side=LEFT).
UsetheTextwidgetinsteadofanEntrywidgetifyouwanttoallowtheuserto
entermultiplelinesoftext.
Typically,anentrywidgetwillappearalongsidealabeldescribingthetypeofinputexpectedtherefromtheuser,oralongsideabuttonwidgetthattheusercanclicktoperformsomeactiononthedatatheyhaveentered,sopositioninginaframeisideal.
Datacurrentlyenteredintoanentrywidgetcanberetrievedbytheprogramusingthatwidget’sget()method.
entry.py
StartanewprogrambymakingGUIfeaturesavailableandmessageboxfeaturesavailableasashortaliasfromtkinterimport*
importtkinter.messageboxasbox
Next,createawindowobjectandspecifyatitle
window=Tk()window.title(‘EntryExample’)
Now,createaframetocontaininganentryfieldforinput
frame=Frame(window)
entry=Entry(frame)
Then,addafunctiontodisplaydatacurrentlyentered
defdialog():box.showinfo(‘Greetings’,‘Welcome’+entry.get())
Now,createabuttontocallthefunctionwhenclicked
btn=Button(frame,text=‘EnterName’,command=dialog)
Addthebuttonandentrytotheframeatsetsides
btn.pack(side=RIGHT,padx=5)
entry.pack(side=LEFT)frame.pack(padx=20,pady=20)
Finally,addthelooptocapturethiswindow’sevents
window.mainloop()
Savethefileandruntheprogram,thenenteryournameandclickthebutton–toseeagreetingmessageappear
ListingoptionsAListboxwidgetprovidesalistofitemsinanapplicationfromwhichtheusercanmakeaselection.Alistboxobjectiscreatedbyspecifyingthenameofitsparentcontainer,suchasawindoworframename,andoptionsasargumentstoaListbox()constructor.Popularoptionsarelistedbelowtogetherwithabriefdescription:
Option: Description:
bd Borderwidthinpixels(defaultis2)
bg Backgroundcolor
fg Foregroundcolorusedtorenderthetext
font Fontforthetext
height Numberoflinesinlist(defaultis10)
selectbackground Backgroundcolorofselectedtext
selectmode SINGLE(thedefault)orMULTIPLEselections
width Listboxwidthinletters(defaultis20)
yscrollcommand Attachtoaverticalscrollbar
Withtkinter,ascrollbarisaseparatewidgetthatcanbeattachedtoListbox,Text,CanvasandEntrywidgets.
Itemsareaddedtothelistboxbyspecifyingalistindexnumberandtheitemstringasargumentstoitsinsert()method.
Youcanretrieveanyitemfromalistboxbyspecifyingitsindexnumberwithintheparenthesesofitsget()method.Usefully,alistboxalsohasacurselection()methodthatreturnstheindexnumberofthecurrentlyselecteditem,sothiscanbesuppliedastheargumenttoitsget()methodtoretrievethecurrentselection.
listbox.py
StartanewprogrambymakingGUIfeaturesavailableandmessageboxfeaturesavailableasashortaliasfromtkinterimport*
importtkinter.messageboxasbox
Next,createawindowobjectandspecifyatitle
window=Tk()window.title(‘ListboxExample’)
Now,createaframetocontainwidgets
frame=Frame(window)
Createalistboxwidgetofferingthreelistitems
listbox=Listbox(frame)
listbox.insert(1,‘HTML5ineasysteps’)listbox.insert(2,‘CSS3ineasysteps’)
listbox.insert(3,‘JavaScriptineasysteps’)
Next,addafunctiontodisplayalistboxselection
defdialog():box.showinfo(‘Selection’,‘YourChoice:’+\
listbox.get(listbox.curselection()))
Now,createabuttontocallthefunctionwhenclicked
btn=Button(frame,text=‘Choose’,command=dialog)
Then,addthebuttonandlistboxtotheframeatsetsides
btn.pack(side=RIGHT,padx=5)listbox.pack(side=LEFT)
frame.pack(padx=30,pady=30)
Finally,addthelooptocapturethiswindow’sevents
window.mainloop()
Savethefileandruntheprogram,thenselectanoptionandclickthebutton–toseeyourselectionconfirmed
PollingradiosARadiobuttonwidgetprovidesasingleiteminanapplicationthattheusermayselect.Whereanumberofradiobuttonsaregroupedtogethertheusermayonlyselectanyoneiteminthegroup.Withtkinter,radiobuttonobjectsaregroupedtogetherwhentheynominatethesamecontrolvariableobjecttoassignavaluetouponselection.AnemptystringvariableobjectcanbecreatedforthispurposeusingtheStringVar()constructororanemptyintegervariableobjectusingtheIntVar()constructor.
Youcannotusearegularvariabletostorevaluesassignedfromaradiobuttonselection–itmustbeanobject.
AradiobuttonobjectiscreatedbyspecifyingfourargumentstoaRadiobutton()constructor:
• Nameoftheparentcontainer,suchastheframename
• Textforadisplaylabel,specifiedasatext=textpair
• Controlvariableobject,specifiedasavariable=variablepair
• Valuetobeassigned,specifiedasavalue=valuepair
Eachradiobuttonobjecthasaselect()methodthatcanbeusedtospecifyadefaultselectioninagroupofradiobuttonswhentheprogramstarts.Astringvalueassignedbyselectingaradiobuttoncanberetrievedfromastringvariableobjectbyitsget()method.
radio.py
StartanewprogrambymakingGUIfeaturesavailableandmessageboxfeaturesavailableasashortaliasfromtkinterimport*
importtkinter.messageboxasbox
Next,createawindowobjectandspecifyatitle
window=Tk()window.title(‘RadioButtonExample’)
Now,createaframetocontainwidgets
frame=Frame(window)
Then,constructastringvariableobjecttostoreaselection
book=StringVar()
Next,createthreeradiobuttonwidgetswhosevaluewillbeassignedtothestringvariableuponselectionradio_1=Radiobutton(frame,text=‘HTML5’,\
variable=book,value=‘HTML5ineasysteps’)radio_2=Radiobutton(frame,text=‘CSS3’,\
variable=book,value=‘CSS3ineasysteps’)radio_3=Radiobutton(frame,text=‘JS’,\
variable=book,value=‘JavaScriptineasysteps’)
Now,addastatementtospecifywhichradiobuttonwillbeselectedbydefaultwhentheprogramstartsradio_1.select()
Then,addafunctiontodisplayaradiobuttonselectionandabuttontocallthisfunctiondefdialog():
box.showinfo(‘Selection’,\
‘YourChoice:\n’+book.get())btn=Button(frame,text=‘Choose’,command=dialog)
Addthepushbuttonandradiobuttonstotheframe
btn.pack(side=RIGHT,padx=5)
radio_1.pack(side=LEFT)radio_2.pack(side=LEFT)
radio_3.pack(side=LEFT)frame.pack(padx=30,pady=30)
Finally,addthelooptocapturethiswindow’sevents
window.mainloop()
Savethefileandruntheprogram,thenchooseanoptionandclickthebutton–toseeyourchoiceconfirmed
CheckingboxesACheckbuttonwidgetprovidesasingleiteminanapplicationthattheusermayselect.Whereanumberofcheckbuttonsappeartogethertheusermayselectoneormoreitems.Checkbuttonobjectsnominateanindividualcontrolvariableobjecttoassignavaluetowhethercheckedorunchecked.AnemptystringvariableobjectcanbecreatedforthisusingtheStringVar()constructororanemptyintegervariableobjectusingtheIntVar()constructor.
AcheckbuttonobjectiscreatedbyspecifyingfiveargumentstoaCheckbutton()constructor:
• Nameoftheparentcontainer,suchastheframename
• Textforadisplaylabel,asatext=textpair
• Controlvariableobject,asavariable=variablepair
• Valuetoassignifchecked,asanonvalue=valuepair
• Valuetoassignifunchecked,asanoffvalue=valuepair
Anintegervalueassignedbyacheckbuttoncanberetrievedfromaintegervariableobjectbyitsget()method.
check.py
StartanewprogrambymakingGUIfeaturesavailableandmessageboxfeaturesavailableasashortaliasfromtkinterimport*
importtkinter.messageboxasbox
Next,createawindowobjectandspecifyatitle
window=Tk()window.title(‘CheckButtonExample’)
Now,createaframetocontainwidgets
frame=Frame(window)
Then,constructthreeintegervariableobjectstostorevalues
var_1=IntVar()
var_2=IntVar()var_3=IntVar()
Createthreecheckbuttonwidgetswhosevalueswillbeassignedtotheinteger
variablewhethercheckedornotbook_1=Checkbutton(frame,text=‘HTML5’,\
variable=var_1,onvalue=1,offvalue=0)book_2=Checkbutton(frame,text=‘CSS3’,\
variable=var_2,onvalue=1,offvalue=0)book_3=Checkbutton(frame,text=‘JS’,\
variable=var_3,onvalue=1,offvalue=0)
Next,addafunctiontodisplayacheckbuttonselection
defdialog():s=‘YourChoice:’
ifvar_1.get()==1:s+=‘\nHTML5ineasysteps’ifvar_2.get()==1:s+=‘\nCSS3ineasysteps’
ifvar_3.get()==1:s+=‘\nJavaScriptineasysteps’box.showinfo(‘Selection’,s)
Now,createabuttontocallthefunctionwhenclicked
btn=Button(frame,text=‘Choose’,command=dialog)
Then,addthepushbuttonandcheckbuttonstotheframe
btn.pack(side=RIGHT,padx=5)
book_1.pack(side=LEFT)book_2.pack(side=LEFT)
book_3.pack(side=LEFT)frame.pack(padx=30,pady=30)
Finally,addthelooptocapturethiswindow’sevents
window.mainloop()
Savethefileandruntheprogram,thencheckboxesandclickthebutton–toseeyourselectionconfirmed
ACheckbuttonobjecthasselect()anddeselect()methodsthatcanbeusedtoturnthestateonoroff.Forexample,check_1.select().
ThestateofanyCheckbuttonobjectcanbereversedbycallingitstoggle()method.
AddingimagesWiththetkintermodule,imagesinGIForPGM/PPMfileformatscanbedisplayedonLabel,Button,TextandCanvaswidgetsusingthePhotoImage()constructortocreateimageobjects.Thissimplyrequiresasinglefile=argumenttospecifytheimagefile.Interestingly,italsohasasubsample()methodthatcanscaledownaspecifiedimagebystatingasamplevaluetox=andy=arguments.Forexample,valuesofx=2,y=2sampleseverysecondpixel–sotheimageobjectishalf-sizeoftheoriginal.
OnceanimageobjecthasbeencreateditcanbeaddedtoaLabelorButtonconstructorstatementbyanimage=option.
ThePhotoImageclassalsohasazoom()methodthatwilldoubletheimagesizewiththesamex=2,y=2values.Textobjectshaveanimage_create()methodwithwhichtoembedanimageintothetextfield.Thisrequirestwoargumentstospecifylocationandimage=.Forexample,‘1.0’specifiesthefirstlineandfirstcharacter.
Canvasobjectshaveacreate_image()methodthatrequirestwoargumentstospecifylocationandimage=.Herethelocationsetsthex,ycoordinatesonthecanvasatwhichtopainttheimage.
image.py
StartanewprogrambymakingGUImethodsandattributesavailablethencreateawindowobjectandspecifyatitlefromtkinterimport*
window=Tk()window.title(‘ImageExample’)
Now,createanimageobjectfromalocalimagefile
img=PhotoImage(file=‘python.gif’)
python.gif(200x200)
Then,createalabelobjecttodisplaytheimageaboveacoloredbackground
label=Label(window,image=img,bg=‘yellow’)
Createahalf-sizeimageobjectfromthefirstimageobject
small_img=PhotoImage.subsample(img,x=2,y=2)
Now,createabuttontodisplaythesmallimage
btn=Button(window,image=small_img)
Createatextfieldandembedthesmallimagetheninsertsometextafterit
txt=Text(window,width=25,height=7)
txt.image_create(‘1.0’,image=small_img)txt.insert(‘1.1’,‘PythonFun!’)
Createacanvasandpaintthesmallimageaboveacoloredbackgroundthenpaintadiagonallineoverthetopofitcan=\
Canvas(window,width=100,height=100,bg=‘cyan’)can.create_image((50,50),image=small_img)
can.create_line(0,0,100,100,width=25,fill=‘yellow’)
Then,addthewidgetstothewindow
label.pack(side=TOP)btn.pack(side=LEFT,padx=10)
txt.pack(side=LEFT)can.pack(side=LEFT,padx=10)
Finally,addthelooptocapturethiswindow’sevents
window.mainloop()
Savethefilethenruntheprogram–toseetheimageontheLabel,Button,TextandCanvaswidgets
NoticethattheTextmethodisimage_create()buttheCanvasmethodiscreate_image()–similaryetdifferent.
TextandCanvaswidgetsarebothpowerfulandflexible–discovermoreonlineatdocs.python.org/3.3/library/tkinter.html
Summary• ThetkintermodulecanbeimportedintoaPythonprogramtoprovideattributesand
methodsforwindowedapplications
• EverytkinterprogrammustbeginbycallingTk()tocreateawindowandcallitsmainloop()methodtocaptureevents
• Thewindowobject’stitleisspecifiedbyitstitle()method
• AlabelwidgetiscreatedbyspecifyingthenameofitsparentcontaineranditstextasargumentstotheLabel()constructor
• Widgetscanbeaddedtoanapplicationusingthepack(),grid()orplace()geometrymanagers
• Abuttonwidgetiscreatedbyspecifyingthenameofitsparentcontainer,itstext,andthenameofafunctiontocallwhentheuserpushesit,asargumentstotheButton()constructor
• Thetkinter.messageboxmodulecanbeimportedintoaPythonprogramtoprovideattributesandmethodsformessageboxes
• Messageboxesthatasktheusertomakeachoicereturnavaluetotheprogramforconditionalbranching
• TheFrame()constructorcreatesacontainerinwhichmultiplewidgetscanbegroupedforbetterpositioning
• TheEntry()constructorcreatesasinglelinetextfieldwhosecurrentcontentscanberetrievedbyitsget()method
• ItemsareaddedtoaListboxobjectbyitsinsert()methodandretrievedbyspecifyingtheirindexnumbertoitsget()method
• RadiobuttonandCheckbuttonobjectsstorevaluesintheStringVarorIntVarobjectnominatedbytheirvariableattribute
• ThePhotoImage()constructorcreatesanimageobjectthathasasubsample()methodwhichcanscaledowntheimage
• ImagescanbeaddedtoButtonandLabelobjects,embeddedinTextobjects,andpaintedonCanvasobjects
12Developingapps
Thischapterbringstogetherelementsfrompreviouschapterstodevelopawindowedapplication.
GeneratingrandomsPlanningneedsDesigninglayoutAssigningstaticsLoadingdynamicsAddingfunctionalityTestingprogramsDeployingapplicationsSummary
GeneratingrandomsThegraphicalapplicationdevelopedonsubsequentpagesofthisbookwillgeneratesixrandomnumberswithinaspecificrange.Initially,itsfunctionalitycanbedevelopedasaconsoleapplicationthentransferredlatertoillustratehowitcanbeappliedtographicalwidgetcomponents.
ThestandardPythonlibraryhasarandommodulethatprovidesmethodstogeneratepseudo-randomnumbers.Thecurrentsystemtimeisusedbydefaultto“seed”therandomgeneratorwheneveritgetsinitialized–soitdoesnotrepeatitsselections.
Apseudo-randomfloating-pointnumberfrom0.0to1.0canbegeneratedbycallingtherandom()methodfromtherandommodule.Therangeofgeneratednumberscanbemodifiedusingthe*multiplicationoperatortospecifyamaximumvalueandcanberoundeddowntointegervaluesusingthebuilt-inint()function.Forexample,togenerateanintegerwithintherangeofzerotonine:int(random.random()*10)
Ortogenerateawholenumberwithintherangeof1to10:int(random.random()*10)+1
Floating-pointnumberscastfromthefloatdatatypetotheintdatatypebythebuilt-inint()functiongettruncatedatthedecimalpoint.Thisstatementcouldbeusedinalooptogeneratemultiplerandomintegerswithinagivenrangebutanynumbermayberepeatedinthatoutput–thereisnoguaranteeduniqueness.Instead,multipleuniquerandomintegerswithinagivenrangecanbegeneratedbythesample()methodfromtherandommodule.Thisrequirestwoargumentstospecifytherangeandthenumberofuniqueintegerstobereturned.Itisconvenienttousethebuilt-inrange()functiontospecifyamaximumvalue.Forexample,togeneratesixuniquenumberswithintherangeof1to9:random.sample(range(10),6)
Ortogeneratesixuniquenumberswithintherangeof1to10:random.sample(range(1,11),6)
Thistechniquecouldrepresentarandomlotteryentrybychoosing,say,sixuniquenumbersbetween1and49.
Therange()functioncanspecifystartandendvalues.Ifnostartingvalueissupplied,zeroisassumedbydefault.
sample.py
Startanewprogrambyimportingtwofunctionsfromthe“random”module
fromrandomimportrandom,sample
Next,assignarandomfloating-pointnumbertoavariablethendisplayitsvalue
num=random()
print(‘RandomFloat0.0-1.0:‘,num)
Now,multiplythefloating-pointnumberandcastittobecomeanintegerthendisplayitsvaluenum=int(num*10)print(‘RandomInteger0-9:‘,num)
Addalooptoassignmultiplerandomintegerstoalist,thendisplaythelistitems
nums=[];i=0
whilei<6:nums.append(int(random()*10)+1)
i+=1print(‘RandomMultipleIntegers1-10:’,nums)
Finally,assignmultipleuniquerandomintegerstothelistthendisplaythelistitemsnums=sample(range(1,49),6)
print(‘RandomIntegerSample1-49:‘,nums)
Savethefilethenruntheprogramseveraltimes–toseethegeneratedrandomnumbers
PlanningneedsWhencreatinganewgraphicalapplicationitisusefultofirstspendsometimeplanningitsdesign.Clearlydefinetheprogram’sprecisepurpose,decidewhatapplicationfunctionalitywillberequired,thendecidewhatinterfacewidgetswillbeneeded.
Aplanforasimpleapplicationtopicknumbersforalotteryentrymightlooklikethis:
Programpurpose
• Theprogramwillgenerateaseriesofsixuniquerandomnumbersintherange1-49andhavetheabilitytobereset
Functionalityrequired
• Afunctiontogenerateanddisplaysixuniquerandomnumbers
• Afunctiontoclearthelastsixrandomnumbersfromdisplay
Interfacewidgetsneeded
• Onenon-resizablewindowtocontainallotherwidgetsandtodisplaytheapplicationtitle.
• OneLabelwidgettodisplayastaticapplicationlogoimage–justtoenhancetheappearanceoftheinterface.
• SixLabelwidgetstodynamicallydisplaythegeneratedseriesofuniquerandomnumbers–onenumberperLabel.
• OneButtonwidgettogenerateanddisplaythenumbersintheLabelwidgetswhenthisButtongetsclicked.ThisButtonwillnotbeenabledwhenthenumbersareondisplay.
• OneButtonwidgettoclearthenumbersondisplayintheLabelwidgetswhenthisButtongetsclicked.ThisButtonwillnotbeenabledwhenthenumbersarenotondisplay.
Havingestablishedaprogramplanmeansyoucannowproducetheapplicationbasicsbycreatingallthenecessarywidgets.
TogglethevalueofaButtonwidget’sstatepropertyfromNORMALtoDISABLEDtosteertheuser–inthiscasetheapplicationmustberesetbeforea
furtherseriesofuniquerandomnumberscanbegenerated.
lotto(widgets).py
Startanewprogrambyimportingallfeaturesfromthe“tkinter”module
#Widgets:
fromtkinterimport*
Next,addstatementstocreateawindowobjectandanimageobject
window=Tk()img=PhotoImage(file=‘lotto.gif’)
lotto.gif
Now,addstatementstocreateallthenecessarywidgets
imgLbl=Label(window,image=img)
label1=Label(window,relief=‘groove’,width=2)label2=Label(window,relief=‘groove’,width=2)
label3=Label(window,relief=‘groove’,width=2)label4=Label(window,relief=‘groove’,width=2)
label5=Label(window,relief=‘groove’,width=2)label6=Label(window,relief=‘groove’,width=2)
getBtn=Button(window)resBtn=Button(window)
Then,addthewidgetstothewindowusingthegridlayoutmanager–readytoreceiveargumentstospecifyhowthewidgetsshouldbepositionedatthedesignstagenext#Geometry:
imgLbl.grid()label1.grid()
label2.grid()label3.grid()
label4.grid()label5.grid()
label6.grid()
getBtn.grid()
resBtn.grid()
Finally,addaloopstatementtosustainthewindow
#Sustainwindow:window.mainloop()
Savethefilethenruntheprogram–toseethewindowappearcontainingallthenecessarywidgets
Thereliefpropertyspecifiesaborderstyleandthewidthpropertyspecifiesthelabelwidthincharacternumbers.
DesigninglayoutHavingcreatedallthenecessarywidgets,onthepreviouspage,youcannowdesigntheinterfacelayoutbyaddingargumentstospecifyhowthewidgetsshouldbepositioned.AhorizontaldesignwillpositionthelogoLabelontheleft,andonitsrightallsixotherLabelsinarowwithbothButtonsbelowthis.Thegridlayoutmanager,whichpositionswidgetsinrowsandcolumns,caneasilyproducethisdesignbyallowingthelogoLabeltospanarowcontainingallsixotherLabelsandalsoarowcontainingbothButtons.OneButtoncanspanfourcolumnsandtheotherButtoncanspantwocolumns,arrangedlikethis:
Thegridlayoutmanager’srowspanandcolumnspanpropertiesworkliketheHTMLrowspanandcolspantablecellattributes.
lotto(layout).py
Edittheprogramstartedonthepreviouspage–firstlybypositioningtheLabelcontainingthelogointhefirstcolumnofthefirstrow,andhaveitspanacrossthesecondrow#Geometry:
imgLbl.grid(row=1,column=1,rowspan=2)
Next,positionaLabelinthesecondcolumnofthefirstrowandadd10pixelsofpaddingtoitsleftandrightlabel1.grid(row=1,column=2,padx=10)
Now,positionaLabelinthethirdcolumnofthefirstrowandadd10pixelsofpaddingtoitsleftandrightlabel2.grid(row=1,column=3,padx=10)
PositionaLabelinthefourthcolumnofthefirstrowandadd10pixelsofpaddingtoitsleftandrightlabel3.grid(row=1,column=4,padx=10)
PositionaLabelinthefifthcolumnofthefirstrowandadd10pixelsofpaddingtoitsleftandrightlabel4.grid(row=1,column=5,padx=10)
PositionaLabelinthesixthcolumnofthefirstrowandadd10pixelsofpaddingtoitsleftandrightlabel5.grid(row=1,column=6,padx=10)
PositionaLabelintheseventhcolumnofthefirstrowthenadd10pixelsofpaddingtotheleftsideoftheLabeland20pixelsofpaddingtotherightsideoftheLabellabel6.grid(row=1,column=7,padx=(10,20))
Next,positionaButtoninthesecondcolumnofthesecondrowandhaveitspanacrossfourcolumnsgetBtn.grid(row=2,column=2,columnspan=4)
Now,positionaButtoninthesixthcolumnofthesecondrow,andhaveitspanacrosstwocolumnsresBtn.grid(row=2,column=6,columnspan=2)
Savethefilethenruntheprogram–toseethewindowappearcontainingallthenecessarywidgetsnowarrangedinyourgridlayoutdesign
ThewindowsizeisautomaticallyadjustedtosuitthegridcontentsandtheButtonwidgetsareautomaticallycenteredinthespannedcolumnwidth.
AdditionalpaddingtotherightoftheLabelinthefinalcolumnofthefirstrowextendsthewindowwidthtosimplycreateasmallright-handmarginarea.
AssigningstaticsHavingarrangedallthenecessarywidgetsinagridlayout,onthepreviouspage,youcannowassignstaticvaluestothewidgets.Thesevalueswillnotchangeduringexecutionoftheprogram.
lotto(static).py
Modifytheprogramonthepreviouspagebyinsertinganewsectionjustbeforethefinalloopstatement,whichbeginswithastatementspecifyingawindowtitle#StaticProperties:
window.title(‘LottoNumberPicker’)
Next,addastatementtopreventtheuserresizingthewindowalongboththeXaxisandtheYaxis–thiswilldisablethewindow’s“resize”buttonwindow.resizable(0,0)
Now,addastatementtospecifytexttoappearonthefaceofthefirstButtonwidgetgetBtn.configure(text=‘GetMyLuckyNumbers’)
Then,addastatementtospecifytexttoappearonthefaceofthesecondButtonwidgetresBtn.configure(text=‘Reset’)
Savethefilethenexecutetheprogram–toseethewindownowhasatitle,itsresizebuttonisdisabled,andthebuttonshavenowbeenresizedtosuittheirtext
Thewidget’sconfigure()methodallowspropertiestobesubsequentlyaddedormodifiedaftertheyhavebeencreated.
LoadingdynamicsHavingspecifiedvaluesforstaticproperties,onthefacingpage,initialvaluescannowbespecifiedforthosepropertieswhosevalueswillchangedynamicallyduringexecutionoftheprogram.
lotto(initial).py
Modifytheprogramonthefacingpagebyinsertinganothernewsectionjustbeforethefinalloopstatement,whichspecifiesthateachsmallemptyLabelshouldinitiallydisplayanellipsis#InitialProperties:
label1.configure(text=‘…’)label2.configure(text=‘…’)
label3.configure(text=‘…’)label4.configure(text=‘…’)
label5.configure(text=‘…’)label6.configure(text=‘…’)
Next,addastatementtospecifythatthesecondButtonwidgetshouldinitiallybedisabledresBtn.configure(state=DISABLED)
Savethefilethenruntheprogram–toseeeachsmallLabelnowdisplaysanellipsisandthatthe“Reset”Buttonhasbeendisabled
ButtonstatesarerecognizedbytkinterconstantsofDISABLED(off),NORMAL(on),orACTIVE(pressed).
AddingfunctionalityHavingcreatedcodetoinitializedynamicproperties,onthepreviouspage,youcannowaddruntimefunctionalitytorespondtoclicksontheButtonwidgetsduringexecutionoftheprogram.
lotto.py
Modifytheprogramonthepreviouspagebyinsertingonemorenewsectionjustbeforethefinalloopstatement,whichbeginsbymakingthesample()functionavailablefromthe“random”module#DynamicProperties:
fromrandomimportsample
Next,defineafunctionthatgeneratesandassignssixuniquerandomnumberstothesmallLabelsandreversesthestateofbothButtonsdefpick():
nums=sample(range(1,49),6)
label1.configure(text=nums[0])label2.configure(text=nums[1])
label3.configure(text=nums[2])label4.configure(text=nums[3])
label5.configure(text=nums[4])label6.configure(text=nums[5])
getBtn.configure(state=DISABLED)resBtn.configure(state=NORMAL)
Now,defineafunctiontodisplayanellipsisoneachsmallLabelandrevertbothButtonstotheirinitialstatesdefreset():
label1.configure(text=‘…’)label2.configure(text=‘…’)
label3.configure(text=‘…’)label4.configure(text=‘…’)
label5.configure(text=‘…’)label6.configure(text=‘…’)
getBtn.configure(state=NORMAL)resBtn.configure(state=DISABLED)
Then,addstatementstonominatetherelevantfunctiontobecalledwheneach
ButtonispressedbytheusergetBtn.configure(command=pick)
resBtn.configure(command=reset)
Finally,savethefile–thecompleteprogramshouldlooklikethatshownbelow
Thesestepsprovidecomparablefunctionalitytothatoftheconsoleapplicationhere.
TestingprogramsHavingworkedthroughtheprogramplan,onthepreviouspages,thewidgetsneededandfunctionalityrequiredhavenowbeenaddedtotheapplication–soit’sreadytobetested.
Launchtheapplicationandexamineitsinitialappearance
StatictextappearsonthewindowtitlebarandontheButtonwidgets,thewindow’sresizebuttonisdisabled,thesmallLabelscontaintheirinitialellipsistextvalues,andthe“Reset”buttonisinitsinitialdisabledstate.
Next,clickthe“GetMyLuckyNumbers”Buttonwidget–toexecuteallthestatementswithinthepick()function
AseriesofnumberswithinthedesiredrangeisdisplayedandtheButtonstateshavechangedasrequired–afurtherseriesofnumberscannotbegenerateduntiltheapplicationhasbeenreset.
Makeanoteofthenumbersgeneratedinthisfirstseriesforcomparisonlater
Nonumberisrepeatedinanyseriesbecausetherandomsample()functionreturnsasetofuniquerandomintegers.
Clickthe“Reset”Buttonwidget–toexecuteallthestatementswithinthereset()functionandseetheapplicationresumeitsinitialappearanceasrequired
Clickthe“GetMyLuckyNumbers”Buttonwidgetagain–toexecuteitspick()functionagainandconfirmthatthenewseriesofnumbersdifferfromthefirstseries
Finally,restarttheapplicationandclickthe“GetMyLuckyNumbers”Buttonwidgetoncemore–andconfirmthatthisfirstseriesofnumbersaredifferenttothosenotedinthefirstserieswhentheapplicationlastran
Theseriesofgeneratednumbersarenotrepeatedeachtimetheapplicationgetslaunchedbecausetherandomgeneratorisseededbythecurrentsystemtime–whichisdifferenteachtimethegeneratorgetscalled.
DeployingapplicationsYourappsdevelopedinthePythonlanguagecanbedeployedonWindowssystemswherethePythoninterpreterisnotinstalled.Todoso,alltheprogramfilesmustbe“frozen”intoabundlethatincludesanexecutable(.exe)filetocreateasimpleMSIinstaller.The“cx_Freeze”toolisafreesetofscriptsandmodulesforfreezingPythonprogramsavailableatcx-freeze.sourceforge.net
Thecx_FreezetoolusesPython’s“distutils”packageandrequiresasetupscripttodescribeyourmoduledistributioninordertobundleappropriatesupportforyourapplication.Thesetupscriptistraditionallynamedsetup.pyandconsistsmainlyofacalltoacx_Freezesetup()function–supplyinginformationasparameterpairs.Thisspecifiesanyrequiredbuildoptions,suchasimagefilesormodulestobeincluded,andidentifiestheexecutablescriptandsystemplatformtype.Forexample,thesetupscriptfortheapplicationdevelopedthroughoutthischaptermustincludethelogoimagefilelotto.gifandspecifythefinalcodescriptnamedlotto.pyastheexecutablescript.Oncecx_Freezeisinstalled,asetupscriptcanbeexecutedfromaWindowsCommandPromptwiththeargumentbdist-msi–tocreateasub-directorynamed“dist”containingadistributableMSIinstallerforyourapp.
Thecx_FreezetoolcanalsocreateexecutablefilesforMacandLinuxsystems.Discovermoreoncx_Freezeonlineatcx_freeze.readthedocs.orgsetup.py
setup.py
InIDLEstartaPythonsetupscriptbymakingavailablethe“sys”moduleanditemsfromthe“cx_Freeze”moduleimportsys
fromcx_Freezeimportsetup,Executable
Next,addstatementstoidentifythebaseplatforminuse
base=Noneifsys.platform==‘win32’:base=‘Win32GUI’
Now,addastatementlistingoptionstobeincluded
opts={‘include_files’:[‘lotto.gif’],‘includes’:[‘re’]}
Finally,addacalltothesetup()functionpassingallinformationasparameterpairs
setup(name=‘Lotto’,
version=‘1.0’,description=‘LotteryNumberPicker’,
author=‘MikeMcGrath’,options={‘build_exe’:opts},
executables=[Executable(‘lotto.py’,base=base)])
SavethesetupscriptalongsidetheapplicationfilesthenrunthescriptcommandtocreatetheWindowsinstaller
Waituntiltheprocesscreatestheinstallerina“dist”sub-directorythencopytheinstallerontoportablemedia,suchasaUSBflashdrive
Now,copytheinstallerontoanotherWindowscomputerwherePythonmaynotbepresentandruntheinstaller
Then,selectaninstallationlocation,oracceptthesuggesteddefaultlocation
Whentheinstallerhasfinishedcopyingfiles,navigatetoyourchoseninstallationlocationandruntheexecutablefile–toseetheapplicationlaunch
Summary• ThestandardPythonlibraryhasarandommodulethatprovidesfunctionstogenerate
pseudo-randomnumbers
• Apseudo-randomfloating-pointnumberfrom0.0to1.0canbegeneratedbytherandommodule’srandom()function
• Multipleuniquerandomintegerswithinagivenrangecanbegeneratedbytherandommodule’ssample()function
• Aprogramplanshoulddefinetheprogram’sPurpose,requiredFunctionality,andtheInterfacewidgetsneeded
• Indesigningaprograminterfacethegrid()layoutmanagerpositionswidgetsinrowsandcolumns
• Staticpropertiesdonotchangeduringexecutionofaprogram
• Dynamicpropertiesdochangeduringexecutionofaprogramusingruntimefunctionalitytorespondtoauseraction
• Uponcompletion,aprogramshouldbetestedtoensureitperformsasexpectedineveryrespect
• Programfilescanbe“frozen”intoabundlefordistributiontoothercomputerswherethePythoninterpreterisnotpresent
• Thecx_FreezetoolusesPython’s“disutils”packagetofreezeprogramsintoexecutablesforWindows,Mac,orLinux
• Asetupscriptdescribesyourmoduledistributionsocx_Freezewillbundleappropriatesupportfortheapplication
• Traditionally,asetupscriptisnamedsetup.pyandconsistsmainlyofacalltothecx_Freezesetup()function
• ApplicationscanbedeployedonWindowssystemsusingthecx_Freezetooltocreateasimpleinstaller
• Whenasetupscriptisexecutedwiththebdist_msicommandanMSIinstalleriscreatedthatwillcopythedistributionbundleontothehostcomputer,includinganexecutablefile
13Transferringskills
Thischapterdemonstratessimilaritiesanddifferencesincodingvariouspopularprogramminglanguages.
UnderstandingcompilersCompilingcodeCodingCCodingC++CodingC#CodingJavaSummary
UnderstandingcompilersModernappsarecodedin“high-level”languagesthatprovideahighlevelofabstractionbetweenmachinecode,whichisunderstoodbycomputers,andsourcecodethatishuman-readable.Inordertorunprogramsthesourcecodemustfirstberenderedintomachinecodethatthecomputercanexecute.Thisprocessisaccomplishedeitherbyan“interpreter”orbya“compiler”dependinguponthelanguageinwhichtheprogramiswritten.
ThePythonprogramminglanguage,usedfordemonstrationthroughoutthepreviouschaptersofthisbook,usesaninterpretertotranslateprogramsourcecode.Asaprogramproceeds,theinterpreterdynamicallytranslatesitsfunctionsandstatementcodeobjectsinto“bytecode”.ThebytecodecanthenbeexecutedviaPython’sbytecodeinterpreter(a.k.a“VirtualMachine”or“VM”).
Oftenlanguagesthatemployaninterpreterarereferredtoas“interpretedlanguages”andthosethatuseacompilerarereferredtoas”compiledlanguages”.
OtherprogramminglanguagesthatemployaninterpretertotranslatesourcecodeintobytecodeforexecutionbythecomputerviatheirvirtualmachineincludeJavaandRuby.
Traditionalprogramminglanguages,suchastheClanguage,useacompilertoconvertprogramsourcecodeintomachinecode.Compilationtakestheentiresourcecodeandfirstgeneratesintermediate“objectcode”representingtheprogram’sfunctionsandstatementsinbinarymachinecodeformat.Thecompilerthencombinestheobjectcodeintoasinglebinarymachinecodefile(.exe)thatcanbeexecuteddirectlybythecomputer.
NoticethattheVirtualMachine(VM)mustbepresentontheuser’scomputertoexecutethoseprogramswrittenininterpretedlanguages.
OtherprogramminglanguagesthatemployacompilertoconvertsourcecodeintomachinecodefordirectexecutionbythecomputerincludeC++(“Cplusplus”)andC#(“Csharp”).
Thereare,therefore,fundamentaldifferencesinthewayprogramswrittenin“interpretedlanguages”,suchasPython,and“compiledlanguages”suchastheClanguage,areexecutedbythecomputer.Eachofferssomeadvantagesanddisadvantagesintermsofperformanceandportability,aslistedinthetablebelow:
Interpreter: Compiler:
Takesindividualcodeobjectsasinputfortranslation Takestheentiresourcecodeasinputforconversion
Doesnotgenerateintermediateobjectcode Doesgenerateintermediateobjectcode
Executesconditionalcontrolstatementsslowly Executesconditionalcontrolstatementsquickly
Requireslittlememoryasobjectcodeisnotgenerated Requiresmorememoryasobjectcodeisgenerated
Translatesthesourcecodeeverytimetheprogramruns Convertsthesourcecodeonceduringcompilation
Reportsanyerrorsimmediatelywhentheyoccurinastatement
Reportsanyerrorsonlyafteranattempttocompiletheentiresourcecode
Programsrunslowerwhilecodeobjectsgetindividuallytranslatedtomachinecode
Programsrunfasterwhilemachinecoderunsdirectlyonthecomputer
Distributedprogramsarehuman-readablesourcecodesoareeasytomodify
Distributedprogramsarecompiledmachinecodesoaredifficulttomodify
Offerspoorerprotectionofintellectualpropertyrights Programsrunfasterwhilemachinecoderunsdirectlyonthecomputer
Don’tbeconfusedbyJavaprograms.Theyare“compiled”intobytecodeasadistributable(.class)filethatnonethelessrequiretheJavaVMbytecodeinterpretertorun.
CompilingcodeTomorefullyunderstandthecompilationprocessitisusefultoexamineindetailthecompilationofasimpleClanguageprogram.InproducinganexecutablefilefromanoriginalCsourcecodefilethecompilationprocessactuallyundergoesfourseparatestages,whicheachgenerateanewfile:
• Preprocessing–thepreprocessorstagefirstsubstitutesall“preprocessor”directives,suchasstatementstoimportlibraries,withtheactuallibrarycode.Forinstance,intheClanguagethelibrarycodeissubstitutedfor#includeimportdirectives.Thegeneratedfilecontainingthesubstitutionsisintextformatandtypicallyhasa.ifileextension
• Translating–thecompilerstagetranslatesthehigh-levelinstructionsinthe.ifileintolow-levelAssemblylanguageinstructions.Thegeneratedfilecontainingthetranslationisintextformatandtypicallyhasa.sfileextension
• Assembling–theassemblerstageconvertstheAssemblylanguagetextinstructionsinthe.sfileintomachinecode.Thegeneratedobjectfilecontainingtheconversionisinbinaryformatandtypicallyhasa.ofileextension
• Linking–thelinkerstagecombinesoneormorebinaryobject.ofilesintoasingleexecutablefile.Thegeneratedfileisinbinaryformatandtypicallyhasa.exefileextension
Strictlyspeaking,“compilation”describesthefirstthreestagesabove,whichoperateona
singlesourcecodetextfileandultimatelygenerateasinglebinaryobjectfile.Wheretheprogramsourcecodecontainssyntaxerrors,suchasamissingstatementterminatororamissingparenthesis,theywillbereportedbythecompilerandcompilationwillfail.
Thelinker,ontheotherhand,canoperateonmultipleobjectfilesandultimatelygeneratesasingleexecutablefile.Thisallowsthecreationoflargeprogramsfrommodularobjectfilesthatmayeachcontainre-usablefunctions.Wherethelinkerfindsafunctionofthesamenamedefinedinmultipleobjectfilesitwillreportanerrorandtheexecutablefilewillnotbecreated.
Normally,thetemporaryfilescreatedduringtheintermediarystagesofthecompilationprocessareautomaticallydeleted,buttheGNUCCompiler(gcc)providesa-save-tempsoptioninthecompilercommandthatallowsthemtobesavedforinspection.
Forasimple“HelloWorld!”programintheClanguage,typeacommandgcchello.c-save-temps-ohello.exethenhitReturntocompileandsavethetemporaryfiles
Openthehello.ifileinaplaintexteditor,suchasWindows’Notepad,toseethesourcecodeappearattheveryendofthefile–precededbysubstitutedlibrarycode
Now,openthehello.sfileinaplaintexteditortoseethetranslationintolow-levelAssemblycodeandnotehowunfriendlythatappearsincontrasttohigh-levelcode
Inthecommandhere,gccinvokesthecompiler,thesourcecodefileishello.c,and-ohello.exespecifiestheexecutablefiletobeoutput.
AcompleteexampledemonstratinghowtocodeandcompileprogramsintheCprogramminglanguageisprovidedoverleaf.
CodingCThecodingdatastructuresandcontrolstructuresdescribedanddemonstratedthroughoutthisbookinthePythonprogramminglanguagealsoexistinotherprogramminglanguages.YourskillsgainedwithPythoncodingcanbetransferredtootherlanguages,suchastheCprogramminglanguage,byrecognizingsimilarities.TheCprogramminglanguageoriginatedwaybackinthe1970sandisdesignedtobeeasilycompiledtolow-levelmachinecode.Itsefficiencymakesitsuitableforawiderangeofapplicationsineverythingfromembeddedsystemstooperatingsystems.
ThesimpleGuessingGameprogram,describedinPythoncodehereandhere,canberecreatedinasimilarCequivalent.
guess.c
StartanewCprogrambyimportinglibrariestomakeinput-output,randomnumber,andtimefunctionsavailable#include<stdio.h>
#include<stdlib.h>#include<time.h>
Next,definea“main”functionbodythatwillenclosetheentiregamecodeandreturnazerovalueoncompletionintmain()
{/*Statementstobeaddedhere*/
return0;}
Now,addstatementstoinitializevariableswitharandomnumberintherange1-20,aBooleantrue,andanintegersrand(time(NULL));
intnum=(rand()%20)+1;intflag=1;
intguess=0;
Addastatementtorequestuserinput
printf(“Guessmynumber1-20:“);
Then,addaloopstatementthatreadsinputintotheintegervariableandwillencloseaconditionaltestwhile(flag==1)
{
scanf(“%d”,&guess);fflush(stdin);/*Conditionaltesttobeaddedhere*/
}
ThisCprogramwillacceptfloating-pointguessesastheirvaluegetstruncatedtoanintegerintheassignmenttotheguessvariable.
Finally,addaconditionaltestinsidetheloopthensave,compile,andruntheprogramif(guess==0){
printf(“Invalid!Enteronlydigits1-20\n”);break;
}elseif(guess<num){printf(“Toolow,tryagain:“);}
elseif(guess>num){printf(“Toohigh,tryagain:“);}else
{printf(“Correct…Mynumberis%d\n”,num);
flag=0;}
TheGNUCCompiler(gcc)iswidelyusedandisfreelyavailableaspartoftheMinimalistGNUforWindows(MinGW)packagefromsourceforge.net/projects/mingwForinstallationinstructionsandotherhelprefertothedocumentationatmingw.org/wiki
GuessingGameinC–programcomparison
• LibraryfunctionsaremadeavailableinCprogramswithan#includedirective,likeusingPython’simportkeyword
• Cprogramsalwayshaveamain()functionthatgetscalledautomaticallywhenevertheprogramruns
• StatementsinCprogramsaregroupedinside{}braces
• VariablesinCarenotlooselytypedsotheirdatatype,suchasint(integer),mustbedefinedintheirdeclaration
• TheendofeachstatementinCmustbedenotedwitha;semi-coloncharacter–tabsandspacesareirrelevant
• ControlstructuresinCprogramsuseif,else,andwhilekeywords–inmuchthesamewayasPythonprograms
CodingC++ThecodingdatastructuresandcontrolstructuresdescribedanddemonstratedthroughoutthisbookinthePythonprogramminglanguagealsoexistintheC++programminglanguage.YourskillsgainedwithPythoncodingcanbetransferredtothatlanguagebyrecognizingitssimilaritiestoPythoncode.TheC++programminglanguageoriginatedbackinthe1980sasanenhancementoftheClanguage,knownas“Cwithclasses”.TheseclassesdefineprogrammingobjectsthattransformtheproceduralnatureofCforobject-orientedprogramminginC++.
ThesimpleGuessingGameprogram,describedinPythoncodehereandhere,canberecreatedinasimilarC++equivalent.
guess.cpp
StartanewC++programbyimportinglibrariestomakeinput-output,randomnumber,andtimefunctionsavailable#include<iostream>
#include<cstdlib>#include<ctime>
Next,definea“main”functionbodythatwillenclosetheentiregamecodeandreturnazerovalueoncompletionintmain()
{/*Statementstobeaddedhere*/
return0;}
Now,addstatementstoinitializevariableswitharandomnumberintherange1-20,aBooleantrue,andanintegersrand(time(0));
intnum=(rand()%20)+1;boolflag=true;
intguess=0;
Addastatementtorequestuserinput
std::cout<<“Guessmynumber1-20:“;
Then,addaloopstatementthatreadsinputintotheintegervariableandwillencloseaconditionaltestwhile(flag==1)
{
std::cin>>guess;std::cin.ignore(256,‘\n’);/*Conditionaltesttobeaddedhere*/
}
ThisC++programwillacceptfloating-pointguessesastheirvaluegetstruncatedtoanintegerintheassignmenttotheguessvariable.
Finally,addaconditionaltestinsidetheloopthensave,compile,andruntheprogramif(guess==0){
std::cout<<“Invalid!Enteronlydigits1-20\n”;
break;}
elseif(guess<num){std::cout<<“Toolow,tryagain:“;}
elseif(guess>num){std::cout<<“Toohigh,tryagain:“;}
else{std::cout<<“Correct…Mynumberis”<<num<<“\n”;
flag=0;}
TheMinimalistGNUforWindows(MinGW)packagefromsourceforge.net/projects/mingwalsooptionallyprovidesacompilerforC++code.Inthecommandherec++invokesthecompiler,thesourcecodefileisguess.cpp,and-oguessplus.exespecifiestheexecutablefiletobeoutput.GuessingGameinC++–programcomparison
• LibraryfunctionsaremadeavailableinC++programswithan#includedirective,likeusingPython’simportkeyword
• C++programsalwayshaveamain()functionthatgetscalledautomaticallywhenevertheprogramruns
• StatementsinC++programsaregroupedinside{}braces
• VariablesinC++arenotlooselytypedsotheirdatatype,suchasint(integer),mustbedefinedintheirdeclaration
• TheendofeachstatementinC++mustbedenotedwitha;semi-coloncharacter–tabsandspacesareirrelevant
• ControlstructuresinC++programsuseif,else,andwhilekeywords–inmuchthesamewayasPythonprograms
CodingC#ThecodingdatastructuresandcontrolstructuresdescribedanddemonstratedthroughoutthisbookinthePythonprogramminglanguagealsoexistintheC#programminglanguage.YourskillsgainedwithPythoncodingcanbetransferredtothatlanguagebyrecognizingitssimilaritiestoPythoncode.TheC#programminglanguagewasdevelopedbyMicrosoftforits.NETinitiative.ProgramsinC#requiretheCommonLanguageRuntime(CLR)tobeinstalledonthehostcomputertoproducemachinecodeatruntime–aprocessknownas“Just-In-Time”(JIT)compilation.
ThesimpleGuessingGameprogram,describedinPythoncodehereandhere,canberecreatedinasimilarC#equivalent.
guess.cs
StartanewC#programbyimportingthenamespacetomakeinput-outputandrandomnumberfunctionsavailableusingSystem;
Next,defineaclassstructuretoenclosetheentiregamecodewithina“Main”functionclassGuess
{staticvoidMain()
{/*Statementstobeaddedhere*/
}};
Now,addstatementstoinitializevariableswitharandomnumberintherange1-20,aBooleantrue,andanintegerRandomgenerator=newRandom();
intnum=generator.Next(1,20+1);boolflag=true;
intguess=0;
Addastatementtorequestuserinput
Console.WriteLine(“Guessmynumber1-20:“);
Then,addaloopstatementthatreadsinputintotheintegervariableandwillencloseaconditionaltestwhile(flag==true)
{
int.TryParse(Console.ReadLine(),outguess);/*Conditionaltesttobeaddedhere*/
}
ThisC#programwillnotacceptfloating-pointguessesastheyareintelligentlyrecognizedasnon-integersbytheint.TryParse()function.
Finally,addaconditionaltestinsidetheloopthensave,compile,andruntheprogramif(guess==0){
Console.Write(“Invalid!Enteronlydigits1-20\n”);
break;}
elseif(guess<num){Console.Write(“Toolow,tryagain:“);}
elseif(guess>num){Console.Write(“Toohigh,tryagain:“);}
else{Console.Write(“Correct…Mynumberis”+num+“\n”);
flag=false;}
TheVisualStudioCommunityIDEisagreatdevelopmentenvironmentforC#programming.Itisavailablefreefromvisualstudio.comandincludestheCSharpCompiler(csc.exe).Inthecommandherecscinvokesthecompiler,/out:guesssharp.exespecifiestheexecutablefiletobeoutput,andthesourcecode
fileisnamedguess.cs.GuessingGameinC#–programcomparison
• LibraryfunctionsaremadeavailableinC#programswithausingdirective,likeusingPython’simportkeyword
• C#programsalwayshaveaclassstructureenclosingaMain()functionthatgetscalledautomaticallywhentheprogramruns
• StatementsinC#programsaregroupedinside{}braces
• VariablesinC#arenotlooselytypedsotheirdatatype,suchasbool(Boolean),mustbedefinedintheirdeclaration
• TheendofeachstatementinC#mustbedenotedwitha;semi-coloncharacter–tabsandspacesareirrelevant
• ControlstructuresinC#programsuseif,else,andwhilekeywords–inmuchthesamewayasPythonprograms
CodingJavaThecodingdatastructuresandcontrolstructuresdescribedanddemonstratedthroughoutthisbookinthePythonprogramminglanguagealsoexistintheJavaprogramminglanguage.YourskillsgainedwithPythoncodingcanbetransferredtothatlanguagebyrecognizingitssimilaritiestoPythoncode.TheJavaprogramminglanguagehastheadmirablemantra“writeonce–runanywhere”.ProgramsinJavarequiretheJavaRuntimeEnvironment(JRE)tobeinstalledonthehostcomputertoproducemachinecodeatruntime–aprocessknownas“Just-In-Time”(JIT)compilation.
ThesimpleGuessingGameprogram,describedinPythoncodehereandhere,canberecreatedinasimilarJavaequivalent.
Guess.java
StartanewJavaprogrambydefiningaclassstructuretoenclosetheentiregamecodewithina“main”functionclassGuess
{publicstaticvoidmain(String[]args)
{/*Statementstobeaddedhere*/
}};
Now,addstatementstoinitializevariableswitharandomnumberintherange1-20,aBooleantrue,andanintegerintnum=(int)(Math.random()*20+1);
booleanflag=true;intguess=0;
Addastatementtorequestuserinput
System.out.print(“Guessmynumber1-20:“);
Then,addaloopstatementthatreadsinputintotheintegervariableandwillencloseaconditionaltestwhile(flag==true)
{try{
guess=Integer.parseInt(System.console().readLine());}catch(NumberFormatExceptionex){}
/*Conditionaltesttobeaddedhere*/
}
ThisJavaprogramwillnotacceptfloating-pointguessesastheyarerecognizedasnon-integersbythefunctionInteger.parseInt().
Finally,addaconditionaltestinsidetheloopthensave,compile,andruntheprogramif(guess==0){
System.out.println(“Invalid!Enteronlydigits1-20”);break;
}elseif(guess<num){
System.out.print(“Toolow,tryagain:“);}elseif(guess>num){
System.out.print(“Toohigh,tryagain:“);}else{
System.out.println(“Correct…Mynumberis”+num);flag=false;
}
TheJavaDevelopmentKit(JDK)isneededtocreateJavaprograms.Itisavailablefreefromoracle.comandincludesthecommand-lineJavaCompiler(javac.exe).InthecommandherejavacinvokesthecompilerforGuess.java
sourcecodeandwillautomaticallyoutputanexecutablefilenamedGuess.exe.ThiscanthenberunbytheJREusingthejavacommand.GuessingGameinJava–programcomparison
• Input-outputandrandomnumberfunctionsarereadilyavailableinJavaprogramswithoutimportstatements
• Javaprogramsalwayshaveaclassstructureenclosingamain()functionthatgetscalledautomaticallywhentheprogramruns
• StatementsinJavaprogramsaregroupedinside{}braces
• VariablesinJavaarenotlooselytypedsotheirdatatype,suchasboolean,mustbedefinedintheirdeclaration
• TheendofeachstatementinJavamustbedenotedwitha;semi-coloncharacter–tabsandspacesareirrelevant
• ControlstructuresinJavaprogramsuseif,else,andwhilekeywords–inmuchthesamewayasPythonprograms
Summary• Modernprogramminglanguages,likePythonorC,provideahighlevelofabstraction
fromlowlevelmachinecode
• Human-readablehigh-levelsourcecodecanberenderedintolow-levelmachinecodebyaninterpreterorbyacompiler
• Interpretedprogramminglanguages,suchasPython,translatesourcecodeintobytecode,whichcanthenbeexecutedviatheirVirtualMachinebytecodeinterpreter
• Compiledprogramminglanguages,suchasC,generateintermediateobjectcodethatgetscombinedintomachinecode,whichcanthenbeexecuteddirectlyonthecomputer
• ThecompilationofaCprogramtranslateshigh-levelsourcecodeintolow-levelAssemblylanguagethenmachinecode
• Intermediatefilesgeneratedduringthecompilationprocessarenormallydeletedautomaticallybythecompiler
• ThedatastructuresandcontrolstructuresusedinPythonalsoexistintheC,C++,C#,andJavaprogramminglanguages–soprogrammingskillsaretransferrableacrosslanguages
• Compiledprogramminglanguages,suchasC,haveamainfunctionthatiscalledautomaticallywhentheprogramruns
• Statementsinmanyprogramminglanguagesaregroupedwithin{}bracesandmustendwitha;semi-colon
• Programminglanguagesthathavestronglytypedvariablesrequirethedatatypethatthevariablemaycontain,suchasintinteger,tobedefinedinthevariabledeclaration
• LikePython,otherprogramminglanguagescanalsoimportfunctionalityfromtheirlibraries
• C#programsrequiretheCommonLanguageRuntime(CLR)tobeinstalledtoproducemachinecodeatruntime
• JavaprogramsrequiretheJavaRuntimeEnvironment(JRE)tobeinstalledtoproducemachinecodeatruntime
Top Related