Top Banner
347

Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Mar 07, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 2: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

MikeMcGrath

CodingforBeginners

Page 3: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

IneasystepsisanimprintofInEasyStepsLimited

16HamiltonTerrace·HollyWalk·LeamingtonSpaWarwickshire·CV324LY

www.ineasysteps.com

Copyright©2015byInEasyStepsLimited.Allrightsreserved.Nopartofthisbookmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageorretrievalsystem,withoutpriorwrittenpermissionfromthepublisher.

NoticeofLiability

Everyefforthasbeenmadetoensurethatthisbookcontainsaccurateandcurrentinformation.However,InEasyStepsLimitedandtheauthorshallnotbeliableforanylossordamagesufferedbyreadersasaresultofanyinformationcontainedherein.

Trademarks

Alltrademarksareacknowledgedasbelongingtotheirrespectivecompanies.

Page 4: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 5: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 6: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 7: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 8: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

1Gettingstarted

Welcometotheexciting,funworldofcomputercoding!Thischapterdescribeshowtocreateyourownprogramming

environmentanddemonstrateshowtocodeyourveryfirstprogram.

ProgrammingcodeSettingupExploringIDLEGettinghelpSavingprogramsStoringvaluesAddingcommentsNamingrulesSummary

Page 9: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 10: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 11: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 12: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 13: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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”

Page 14: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

ClickonNexttobegincopyingfilesontoyourcomputerthenclicktheFinishbuttontocompletetheinstallation

UponcompletionthePythongroupisaddedtoyourStart/Appsmenu.MostimportantofthisgroupistheIDLEitemthatlaunchesthePythonintegrateddevelopmentenvironment.

AddingPythontothesystemPathmakesitavailablefromwithinanydirectory.Afterinstallation,youcanexactlyenterthecommandpython-VataCommandPrompttoseetheinterpreterrespondwithitsversionnumber.

YouwillusetheIDLElauncheroftensoright-clickonitsiconandchoose“Pintotaskbar”tomakeitreadilyavailablefromtheWindowsDesktop.

Page 15: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 16: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 17: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Now,enterthissumstatementattheinteractiveprompt

8+4

Spacesinstatementsareignored–so8+4canbeenteredwithoutspaces.

HitReturntoseetheinterpreterprinttheresulttotal

Enterthisinvalidstatementattheinteractiveprompt

8/0

HitReturntoseetheinterpreterprintanerrormessage

TheShellWindowismostlyusedtotestsnippetsofcode.

Page 18: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 19: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

GettinghelpTheIDLEShellWindowprovidesagreatHelputilitywhereyoucanfindhelponanyPythontopicwhencodingPythonprograms.HelpcanbesoughtbyenteringaPythonhelp()statementattheinteractive>>>prompt.Awelcomemessageappearsandthepromptchangestohelp>todenoteyouarenowinHelpmode.

OpenanIDLEShellWindowthenpreciselyenterthisstatementattheinteractiveprompthelp()

Next,hittheReturnkeytoenterHelpmode

Now,enterthistopicnameattheHelputilitypromptkeywords

HitReturntolistallkeywordsofthePythonlanguage

TheHelputilitywelcomemessagealsocontainshandyhints–butareomittedhereforbrevity.

Keywordsarethevocabularyofaprogramminglanguage.NotethatPythonkeywordsarecase-sensitive–theseareallinlowercaseexceptFalse,None,andTrue.

Page 20: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Then,enterthiscommandattheHelputilitypromptquit

HitReturntoexitHelpandreturntoaninteractiveShellWindowprompt

Therearenoparenthesesrequiredafterthequitinstruction–hereitisaHelputilitycommand,notaPythonstatement.

Whenyoujustwanthelponasingletopicyoucansimplyenterthetopicnamewithinquotemarksinsidetheparenthesesofahelp()statementattheinteractiveprompt:

Preciselyenterthisstatementattheinteractiveprompt

help(‘keywords’)

HitReturntolistallkeywordsofthePythonlanguageandremainataninteractiveShellWindowprompt

Keywordshavespecialmeaninginaprogramminglanguage–theycannotbeusedtonameitemsinyourcode.

Page 21: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 22: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 23: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

helloworld.py

Now,intheIDLEEditWindow,preciselyenterthiscode

print(‘HelloWorld!’)

Next,intheIDLEEditWindow,selecttheFile,Savemenuitems,toopentheSaveAsdialog,thensaveyourprogramcodeasafilenamedhelloworld.py

Finally,intheIDLEEditWindow,selecttheRun,RunModulemenuitems,torunyourprogramcodeandseetheoutputappearintheShellWindow

Yourprogramcodecanbesavedatanyconvenientlocationonyourcomputer–hereitissavedinadirectorycreatedatC:\MyCodethatwillbeusedforallexamplesinthisbook.

NoticethattheShellWindowrestartswheneveritrunsyourprogramcodeafresh.

Page 24: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 25: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 26: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 27: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 28: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

AddingcommentsWhenyoubegintocodelongerprogramsitisusefultoaddcommentsatthestartofeachpieceofcodedescribingthepurposeofthatpiece.Thismakesthecodemoreeasilyunderstoodbyothers,andbyyourselfwhenrevisitingthecodeatalaterdate.InthePythonprogramminglanguageeverythingonasinglelineaftera#hashcharacterisignoredbytheinterpreter.Thismeansthatasingle-linecommentcanbeinsertedaftera#character.

comment.py

OpenanIDLEEditWindowthenentercommentedcodetoinitializeavariableanddisplayitsstatus#Initializeprogramstatus

running=Trueprint(‘Runstate:‘,running)

Savethefilethenruntheprogramtoseethecommentgetignoredandthestoredvaluedisplayedinoutput

Toreadilyidentifyaspectsofyourcode,IDLEautomaticallycolorizesyourcode,bothintheShellWindowandtheEditWindow,withthedefaultcolorslistedinthetablebelow:

CodelistedinthestepsthroughoutthisbookalsousethedefaultIDLEcolorsfor

Page 29: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

consistency.

Page 30: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 31: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 32: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

CANNOTcontainarithmeticoperators a+b*c

CANNOTcontainsymbols %$#@!

CANNOTcontainanyspaces nospaces

CANNOTstartwithanumber 2bad

CANcontainnumberselsewhere good1

CANcontainlettersofmixedcase UPdown

CANcontainunderscores is_ok

Variablenamesarecase-sensitiveinPython–sovariablesnamed“VAR”,“Var”,and“var”wouldbetreatedasthreeseparatevariables.

Page 33: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 34: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 35: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

2Savingdata

Thischapterdemonstrateshowtocreatecodetousevarioustypesofdatastoredinsideyourprograms.

StoringinputControllingoutputRecognizingtypesConvertingdataGuessinggameCorrectingerrorsSummary

Page 36: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 37: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 38: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Thereisnoneedtoincludespacesinthecomma-separatedlists–theyareignoredbytheinterpreterbutareshownhereforclarity.

Page 39: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 40: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 41: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Noticethatthestringshavebeeneditedtonicelyformattheoutput.

Page 42: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 43: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 44: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 45: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Thecomparisonhereexamineswhether4isgreaterthan8,whichisofcourseuntrue.Comparisonsaredemonstratedfullyinthenextchapter.

Page 46: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 47: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 48: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 49: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Ifyouforgettoconverttothecorrectdatatypetheinterpreterwillreportanerror–tryaddinganinttoastrdatatypetoseetheerrormessage.

Page 50: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 51: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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)

Page 52: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 53: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

• Theelsekeywordspecifiesafinalalternativeactiontochangetheprogramcondition,therebyendingtheprogram

Youneednotyetunderstandthisprogramindetail–eachaspectisexplainedbyexampleslaterinthisbook.

Page 54: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 55: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 56: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

TheredsyntaxerrorindicatorpointstothelinewheretheEndOfLine(EOL)erroroccurs.

Insertaquotemarkbeforetheclosingparenthesistoterminatethestringandsavethenruntheprogramagain–toseetheerrorhasbeencorrected

runtime.py

Next,beginanewprogrambyinitializingavariablethentrytooutputitsvaluewithanincorrectvariablename–toseetheinterpreterreportaruntimeerrortitle=‘CodingforBeginnersineasysteps’

print(titel)

Amendthevariablenametomatchthatinthevariabledeclarationandsavethenruntheprogramagain–toseetheerrorhasbeencorrected

semantic.py

Now,beginanewprogrambyinitializingavariablethentrytooutputanexpressionusingitsvaluewithoutexplicitprecedence–toseeapossiblyunexpectedresultof28

Page 57: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

num=3

print(‘Result:‘,num*8+4)

Addparenthesestogrouptheexpressionas3*(8+4)thensavethefileandruntheprogramagain–toseetheexpectedresultof36,correctingthesemanticerror

DetailsofhowtohandleruntimeExceptionerrorsinyourscriptcodeareprovidedhere.

Page 58: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 59: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 60: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

3Performingoperations

Thischapterdemonstrateshowtouseoperatorsymbolsinyourcodestatements.

DoingarithmeticAssigningvaluesComparingvaluesFindingtruthTestingconditionSettingorderSummary

Page 61: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 62: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 63: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 64: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Here,thespecial\tcharactersequenceaddsaninvisibletabcharactertoformattheoutput.

Youcanusethesepparametertoexplicitlyspecifytheseparationbetweenoutput–here,itspecifiesnospacesbyassigningtwounspacedsinglequotemarks.

Page 65: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 66: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 67: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 68: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Unlikethe=assignoperator,the==equalityoperatorcomparesoperandsandisdescribedhere.

Page 69: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 70: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 71: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 72: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

The\tescapesequenceshownhereaddsaninvisibletabcharactertoformattheoutput.

TheASCIIcodevalueforuppercase“A”is65butforlowercase“a”it’s97–sotheircomparisonherereturnsFalse.

Page 73: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 74: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 75: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 76: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

NotethattheexpressionFalseandFalsereturnsFalse,notTrue–perhapsdemonstratingthemaxim“twowrongsdon’tmakearight”.

Page 77: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 78: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 79: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 80: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

YoumayfindthatsomePythonprogrammersdislikeconditionalexpressionsastheyconsideritssyntaxcontradictstheprincipleofeasyreadability.

Page 81: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 82: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 83: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

=,%=,/=,//=,-=,+=,*=,**= 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))

Page 84: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 85: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 86: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 87: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

4Makinglists

Thischapterdemonstrateshowtocreatecodetostoredatainlistsandhowtoretrievedatafromlists.

WritinglistsChanginglistsFixinglistsSettinglistsNamingelementsSummary

Page 88: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 89: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 90: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 91: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Stringindicesmayalsobenegativenumbers–tostartcountingfromtherightwhere-1referencesthelastletter.

Loopstructures,whichareintroducedlaterinthischapter,areoftenusedtoiteratethroughlistelements.

Page 92: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 93: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 94: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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)

Page 95: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

delbasket[1:3]

print(‘SliceRemoved:’,basket)

Savethenrunthisprogram–toseelistsgetmanipulated

Thelastindexnumberintheslicedenotesatwhatpointtostopremovingelements–buttheelementatthatpositiondoesnotgetremoved.

Page 96: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 97: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 98: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 99: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 100: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 101: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 102: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Noticethatthelist()functionmaynotplaceelementvaluesinthesameorderastheyappearintheset.

Page 103: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 104: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 105: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 106: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Noticethatquoteswithinastringmustbeprecededbyabackslashescapecharacter–topreventthestringbeingprematurelyterminated.

Page 107: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 108: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 109: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

5Controllingblocks

Thischapterdemonstrateshowtocreatecodetocontroltheflowofyourprograms.

BranchingchoicesCountingloopsLoopingconditionsSkippingloopsCatchingerrorsSummary

Page 110: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 111: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 112: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 113: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Theuserinputisreadasastringvaluebydefaultsomustbecastasanintdatatypewithint()forarithmeticalcomparison.

TheandkeywordensurestheevaluationisTrueonlywhenbothtestssucceed,whereastheorkeywordensurestheevaluationisTruewheneithertestsucceeds.

Page 114: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 115: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 116: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 117: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Inprogrammingterms,anythingthatcontainsmultipleitemsthatcanbeloopedoverisdescribedas“iterable”.

Page 118: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 119: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 120: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 121: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Theoutputprintedfromtheinnerloopisindentedfromthatoftheouterloopbythe\ttabcharacter.

The+=assignmentstatementi+=1issimplyashorthandwaytosayi=i+1–youcanalsouse*=/=-=shorthandtoassignvaluestovariables.

Page 122: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 123: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 124: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 125: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

continue.py

Thecontinuestatementskipsthefirstiterationoftheinnerloopwhentheouterloopfirstrunsit.

Page 126: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 127: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 128: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 129: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Statementsinthetryblockareallexecutedunlessoruntilanexceptionoccurs.

Page 130: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 131: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 132: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

6Creatingfunctions

Thischapterdemonstrateshowtocodere-usableblocksofcodeinyourprograms.

DefiningblocksAddingparametersReturningresultsStoringfunctionsImportingfunctionsSummary

Page 133: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 134: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 135: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 136: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Variablesthatarenotglobalbutappearinsomeouterscopecanbeaddressedusingthenonlocalkeyword.

Page 137: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 138: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 139: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 140: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Argumentsaretheactualdatavaluespassedtofunctionparametersbythefunctioncall.

Page 141: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 142: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 143: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 144: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

orfloatdatatypeforarithmetic.

Page 145: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 146: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 147: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 148: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Youcancreateanaliaswhenimportingamoduleusingimportaskeywords.Forexample,importcatastomallowsyoutousetomasthefunctionprefixincalls.

Page 149: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 150: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 151: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 152: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

fido.py

Forlargerprogramsyoucanimportmodulesintoothermodulestobuildamodulehierarchy.

Page 153: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 154: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 155: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

7Sortingalgorithms

Thischapterdemonstrateshowtocodeavarietyofsortingalgorithminstructionsequences.

CopyingsortsSelectingsortsInsertingsortsBubblingsortsMergingsortsPartitioningsortsSummary

Page 156: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 157: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

CopyingsortsAn“algorithm”isawell-definedsequenceofinstructionstoperformaspecifictask.Eachalgorithmtakesoneormorevaluesasinputandproducesoneormoreresultingvaluesasoutput.

Analgorithmmaybecreatedincodeasafunctionwhosestatementsdefineasequenceofinstructionstoperformthetask.Inputvaluescanbepassedasargumentsinthefunctioncallandresultingvaluescanbereturnedasoutputfromthefunction.Algorithmscanbecoded,usingdatastructuresandcontrolstructuresinavarietyofways,toperformtaskssuchassortinglistsintoorder.

Pythonprovidesthesort()methodforlists(describedhere)butexamplesinthischapterdemonstratehowtocodevarioussortingalgorithmsthatarefoundinmanyprogramminglanguages.

Sortingefficiencymaydependuponthenatureofthelisttobesortedsodifferentalgorithmsmaybebest-suitedtoparticulartasks.Wherethetaskrequiresalisttobesorted,whiletheoriginalunsortedlistremainsintact,analgorithmfunctioncanbepassedareferencetothelistinanargumentasinput.Thefunctioncanthenmakeacopyoftheoriginallist,sortelementsofthatcopyintoorder,thenreturnthesortedcopylistasoutput.Thisalgorithmsimplycopieselementvaluesfromtheoriginallistintoanewlistarraythenarrangestheminascendingvalueorder.

Page 158: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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)

Page 159: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Eachvalueispoppedoffthelistcopyinsequence–tobuildthesortedversionbyappendingeachtotheemptyarray.

Page 160: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 161: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

SelectingsortsOftenyouwillwanttosorttheelementsofanunsortedlistarray“inplace”ratherthansortacopyoftheoriginallist,asdemonstratedinthepreviousexample.Thereareseveralpopularalgorithmsyoucanemploytosortarraysinplace,eachusingadifferenttechniquewiththeirownstrengthsandweaknesses.

A“selectionsort”algorithmexamineseachelementintheunsortedpartofanarraylistandselectstheelementcontainingthelowestvalue.Itthenswapstheselectedelementvaluewiththatcontainedintheelementatthebeginningoftheunsortedpartofthearraylist–therebyincreasingthesizeofthesortedpartofthearrayanddecreasingitsunsortedpart.Thisprocessisrepeateduntilallelementvaluesaresortedintoascendingorder.

Selectionsortisasimpleswap-basedalgorithmthatisrelativelyeasytounderstandandcodeasafunctionalgorithm.Itisoneofthetwomostefficientalgorithmsforsortingsmallarraysof20orsoelements.

Inthisexample,thefinalelementwillalreadycontainthehighestvaluewhenthepenultimateelementhasbeensorted.

selection.py

Startanewprogrambydeclaringafunctiontoreceivealistreferenceasinputandbeginalooptostoreeachelement’svalueandcurrentindexnumberdefselection_sort(array):

Page 162: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 163: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 164: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 165: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 166: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 167: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 168: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 169: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 170: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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)

Page 171: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 172: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 173: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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)

Page 174: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 175: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 176: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Summary• Analgorithmisawell-definedsequenceofinstructionstoperformaspecifictask

• Eachalgorithmtakesoneormorevaluesasinputandproducesoneormoreresultingvaluesasoutput

• Analgorithmmaybecreatedincodeasafunctionwhosestatementsdefineasequenceofinstructionstoperformatask

• Theefficiencyofsortingalgorithmsmaydependuponthenatureofthelisttobesorted

• Asortingalgorithmfunctioncanmakeacopyofalistpassedasinputandreturnasortedcopyofthatlistasoutput

• Thereareseveralpopularalgorithmstosortarraylistsinplacebuteachhavetheirownstrengthsandweaknesses

• SelectionSortalgorithmsrepeatedlyselectthelowestelementintheunsortedsectionofanarraylistandmoveittotheendofthesortedsectionofthatarray

• InsertionSortalgorithmsrepeatedlytakethenextelementintheunsortedsectionofanarraylistandinsertitintothesortedsectionofthatarrayatthecorrectposition

• BubbleSortalgorithmsrepeatedlycompareadjacentelementsinanunsortedarraylistandswapthemintothecorrectorder

• SelectionSort,InsertionSort,andBubbleSortaresimplecomparisonalgorithmsbutarerelativelyslow

• MergeSortalgorithmsrepeatedlydivideanunsortedarraylistintoleftandrightsub-sectionsfromthearray’smid-pointthenmergethesub-sectionsintoasinglesortedlist

• QuickSortalgorithmsrepeatedlydivideanunsortedarraylistintopartitionscontainingvaluesgreaterorlessthanapivotvaluethenmergethepartitionsintoasinglesortedlist

• MergeSortandQuickSortalgorithmsarefastcomplexalgorithmsthateachemployadivide-and-conquerstrategy

Page 177: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

8Importinglibraries

Thischapterdemonstrateshowtocodepre-definedlibraryfunctionalityintoyourprograms.

InspectingPythonDoingmathematicsCalculatingdecimalsTellingtimeRunningtimersSummary

Page 178: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 179: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 180: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

ThefirstitemonthePythonsearchpathisyourcurrentdirectory–soanyfilewithinthereorwithinanysubdirectoriesyoumaketherewillbefoundbythePythoninterpreter.

SpendalittletimewiththeInteractiveModehelputilitytodiscoverlotsmoreaboutPython.

Page 181: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 182: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 183: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 184: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 185: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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)

Page 186: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 187: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

AlwaysusetheDecimal()objecttocalculatemonetaryvaluesoranywherethataccuracyisessential.

Page 188: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 189: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 190: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

%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

Page 191: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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)

Page 192: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 193: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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)

Page 194: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 195: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Donotconfusethetime.strftime()functionusedinthisexamplewiththedatetime.strftime()functionusedinthepreviousexample.

Page 196: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 197: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 198: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

9Managingtext

Thischapterdemonstrateshowtomanipulatetextstringsinyourprogramsandhowtostoretextinfiles.

ManipulatingstringsFormattingstringsModifyingstringsAccessingfilesManipulatingcontentUpdatingcontentSummary

Page 199: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 200: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 201: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 202: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Rememberthatstringsmustbeenclosedwithineithersinglequotemarksordoublequotemarks.

Withrangeslice,ifthestartindexnumberisomittedzeroisassumedandiftheendindexnumberisomittedthestringlengthisassumed.

Page 203: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 204: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 205: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 206: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Otherdatatypescanbesubstitutedusing%dforadecimalinteger,%cforacharacter,and%fforafloating-pointnumber.

Page 207: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 208: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 209: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 210: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Withtherjust()functionaRIGHT-justifiedstringgetspaddingaddedtoitsLEFT,andwiththeljust()functionaLEFT-justifiedstringgetspaddingaddedtoitsRIGHT.

Page 211: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 212: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 213: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 214: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Ifyourprogramtriestoopenanon-existentfileinrmodetheinterpreterwillreportanerror.

Page 215: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 216: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 217: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

LaunchtheNotepadtexteditortoconfirmthenewtextfileexistsandrevealitscontentswrittenbytheprogram

Now,addstatementsattheendoftheprogramtoappendacitationtothetextfilethensavethescriptfileagainfile=open(‘poem.txt’,‘a’)

file.write(‘(OscarWilde)’)file.close()

Savethenruntheprogramagaintore-writethetextfilethenviewitscontentsinNotepad–toseethecitationnowappendedaftertheoriginaltextcontent

Writingtoanexistingfilewillautomaticallyoverwriteitscontents!

Suppressthedefaultnewlineprovidedbytheprint()functionwherethestringsthemselvescontainnewlines.

Page 218: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Youcanalsousethefileobject’sreadlines()functionthatreturnsalistofalllinesinafile–onelineperelement.

Page 219: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 220: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 221: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 222: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Aswithstrings,thefirstcharacterinafileisatindexpositionzero–notatindexpositionone.

Page 223: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 224: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 225: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

10Programmingobjects

Thischapterdemonstrateshowtocodevirtualobjectsintoyourprograms.

DefiningclassesCopyinginstancesAddressingpropertiesDerivingclassesOverridingmethodsApplyingsenseSummary

Page 226: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 227: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 228: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 229: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Whileaprogramclasscannotperfectlyemulateareal-worldobject,theaimistoencapsulateallrelevantattributesandactions.

Page 230: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 231: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 232: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 233: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Birdinstance–harry

Savebothfilesthenruntheprogram–toseetwoinstancesoftheBirdclassgetcreated

TheclassvariablecountcanalsobereferencedwithBird.countbuttheencapsulatedinstancevariablesoundcanonlybeaccessedbycallinganinstance’stalk()method.

Page 234: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 235: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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’

Page 236: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 237: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Thisloopskipsanyattributewhosenamebeginswithanunderscore,so“private”attributeswillnotgetdisplayedinthelist.

Page 238: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 239: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 240: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 241: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Savethenruntheprogram–toseeoutputgetdisplayedusinginheritedfeatures

inherit.py

Aclassdeclarationcanderivefrommorethanoneclassbylistingmultiplebaseclassesintheparenthesesafteritsnameinthedeclaration.

Don’tconfuseclassinstancesandderivedclasses–aninstanceisacopyofaclass,whereasaderivedclassisanewclassthatinheritspropertiesofthebaseclassfromwhichitisderived.

Page 242: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 243: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 244: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 245: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Man–Richard

Hombre–Ricardo

Themethoddeclarationinthederivedclassmustexactlymatchthatinthebaseclasstooverrideit.

Page 246: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 247: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 248: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 249: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Duck–donald

Mouse–mickey

Aclasscanhaveonlyonemethodwithagivenname–methodoverloadingisnotsupportedinPython.

ObjectOrientedProgrammingwithPythonallowsdataencapsulation,inheritance,andpolymorphism.Baseclassmethodscanbeoverriddenbylike-namedmethodsinderivedclasses.Pythondoesnot,however,supportthetechniqueof“overloading”foundinotherlanguages–inwhichmethodsofthesamenamecanbecreatedwithdifferentparameterlistsinasingleclass.

Page 250: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 251: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 252: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

11Buildinginterfaces

Thischapterdemonstrateshowtocodegraphicalwindowedprograms.

LaunchinginterfacesRespondingbuttonsDisplayingmessagesGatheringentriesListingoptionsPollingradiosCheckingboxesAddingimagesSummary

Page 253: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 254: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 255: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 256: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 257: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 258: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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)

Page 259: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Finally,addthelooptocapturethiswindow’sevents

window.mainloop()

Savethenruntheprogramandclickthebutton–toseethewindow’sbackgroundcolorchange

Onlythefunctionnameisspecifiedtothecommandoption.Donotaddtrailingparenthesesintheassignment.

The‘gray’coloristheoriginaldefaultcolorofthewindow.

Page 260: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 261: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 262: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 263: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Optionscanbeaddedasathirdargumenttothesemethodcalls.Forexample,addtype=’abortretryignore’togetthreebuttons.

Page 264: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 265: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 266: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 267: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

UseaLabelwidgetinsteadofanEntrywidgetifyouwanttodisplaytextthattheusercannotedit.

Page 268: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 269: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 270: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 271: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

IftheselectmodeissettoMULTIPLE,thecurselection()methodreturnsatupleoftheselectedindexnumbers.

Page 272: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 273: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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)

Page 274: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 275: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

ARadiobuttonobjecthasadeselect()methodthatcanbeusedtocancelaselectionprogramatically.

Page 276: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 277: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 278: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 279: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

ACheckbuttonobjecthasselect()anddeselect()methodsthatcanbeusedtoturnthestateonoroff.Forexample,check_1.select().

ThestateofanyCheckbuttonobjectcanbereversedbycallingitstoggle()method.

Page 280: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 281: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 282: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 283: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

NoticethattheTextmethodisimage_create()buttheCanvasmethodiscreate_image()–similaryetdifferent.

TextandCanvaswidgetsarebothpowerfulandflexible–discovermoreonlineatdocs.python.org/3.3/library/tkinter.html

Page 284: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 285: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 286: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

12Developingapps

Thischapterbringstogetherelementsfrompreviouschapterstodevelopawindowedapplication.

GeneratingrandomsPlanningneedsDesigninglayoutAssigningstaticsLoadingdynamicsAddingfunctionalityTestingprogramsDeployingapplicationsSummary

Page 287: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 288: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 289: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 290: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Therandom.sample()functionreturnsalistbutdoesnotactuallyreplaceanyelementsinthespecifiedrange.

Page 291: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 292: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 293: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 294: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

getBtn.grid()

resBtn.grid()

Finally,addaloopstatementtosustainthewindow

#Sustainwindow:window.mainloop()

Savethefilethenruntheprogram–toseethewindowappearcontainingallthenecessarywidgets

Thereliefpropertyspecifiesaborderstyleandthewidthpropertyspecifiesthelabelwidthincharacternumbers.

Page 295: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 296: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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)

Page 297: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 298: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

TheButtonswillexpandtofitstatictextthatwillappearoneachButtonface–specifiedinthenextstage.

Page 299: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 300: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 301: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 302: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 303: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 304: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 305: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

ButtonispressedbytheusergetBtn.configure(command=pick)

resBtn.configure(command=reset)

Finally,savethefile–thecompleteprogramshouldlooklikethatshownbelow

Thesestepsprovidecomparablefunctionalitytothatoftheconsoleapplicationhere.

Page 306: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Itisconventiontoplaceallimportstatementsatthestartofthescriptbuttheycanappearanywhere,aslistedhere.

Page 307: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 308: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 309: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Clickthe“GetMyLuckyNumbers”Buttonwidgetagain–toexecuteitspick()functionagainandconfirmthatthenewseriesofnumbersdifferfromthefirstseries

Finally,restarttheapplicationandclickthe“GetMyLuckyNumbers”Buttonwidgetoncemore–andconfirmthatthisfirstseriesofnumbersaredifferenttothosenotedinthefirstserieswhentheapplicationlastran

Theseriesofgeneratednumbersarenotrepeatedeachtimetheapplicationgetslaunchedbecausetherandomgeneratorisseededbythecurrentsystemtime–whichisdifferenteachtimethegeneratorgetscalled.

Page 310: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 311: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 312: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 313: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

Lotto-1.0-win32.msi

lotto.exe

Page 314: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 315: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 316: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

13Transferringskills

Thischapterdemonstratessimilaritiesanddifferencesincodingvariouspopularprogramminglanguages.

UnderstandingcompilersCompilingcodeCodingCCodingC++CodingC#CodingJavaSummary

Page 317: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 318: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 319: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 320: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 321: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 322: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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.

Page 323: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

AcompleteexampledemonstratinghowtocodeandcompileprogramsintheCprogramminglanguageisprovidedoverleaf.

Page 324: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 325: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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)

Page 326: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

{

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

Page 327: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

GuessingGameinC–programcomparison

• LibraryfunctionsaremadeavailableinCprogramswithan#includedirective,likeusingPython’simportkeyword

• Cprogramsalwayshaveamain()functionthatgetscalledautomaticallywhenevertheprogramruns

• StatementsinCprogramsaregroupedinside{}braces

• VariablesinCarenotlooselytypedsotheirdatatype,suchasint(integer),mustbedefinedintheirdeclaration

• TheendofeachstatementinCmustbedenotedwitha;semi-coloncharacter–tabsandspacesareirrelevant

• ControlstructuresinCprogramsuseif,else,andwhilekeywords–inmuchthesamewayasPythonprograms

Page 328: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 329: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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)

Page 330: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

{

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

Page 331: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

• 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

Page 332: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 333: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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)

Page 334: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

{

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

Page 335: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 336: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 337: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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*/

Page 338: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

}

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

Page 339: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

sourcecodeandwillautomaticallyoutputanexecutablefilenamedGuess.exe.ThiscanthenberunbytheJREusingthejavacommand.GuessingGameinJava–programcomparison

• Input-outputandrandomnumberfunctionsarereadilyavailableinJavaprogramswithoutimportstatements

• Javaprogramsalwayshaveaclassstructureenclosingamain()functionthatgetscalledautomaticallywhentheprogramruns

• StatementsinJavaprogramsaregroupedinside{}braces

• VariablesinJavaarenotlooselytypedsotheirdatatype,suchasboolean,mustbedefinedintheirdeclaration

• TheendofeachstatementinJavamustbedenotedwitha;semi-coloncharacter–tabsandspacesareirrelevant

• ControlstructuresinJavaprogramsuseif,else,andwhilekeywords–inmuchthesamewayasPythonprograms

Page 340: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 341: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling

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

Page 342: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 343: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 344: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 345: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 346: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling
Page 347: Coding for Beginners in easy steps: Basic programming for ...1.droppdf.com/files/dkZRf/coding-for-beginners-in-easy-steps-basic-programming-for-all...Understanding compilers Compiling