introduction to programming with python
TRANSCRIPT
Disclaimer
ALLRIGHTSRESERVED.ThisbookcontainsmaterialprotectedunderInternationalandFederalCopyrightLawsandTreaties.Anyunauthorizedreprintoruseofthismaterialisprohibited.Nopartofthisbookmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageandretrievalsystemwithoutexpresswrittenpermissionfromtheauthor/publisher.
Anyunauthorizedbroadcasting;publicperformance,copyingorre-recordingwillconstituteaninfringementofcopyright.
Permissiongrantedtoreproduceforpersonalandeducationaluseonly.Commercialcopying,hiring,lendingisprohibited.
Maybeusedfreeofcharge.Sellingwithoutpriorwrittenconsentprohibited.Obtainpermissionbeforeredistributing.Inallcasesthisnoticemustremainintact.
FURTHERINFORMATION:LimitOfLiability/DisclaimerOfWarranty:ThePublisherAndTheAuthorMakeNoRepresentationsOrWarrantiesWithRespectToTheAccuracyOrCompletenessOfTheContentsOfThisWorkAndSpecificallyDisclaimAllWarranties,IncludingWithoutLimitationWarrantiesOfFitnessForAParticularPurpose.NoWarrantyMayBeCreatedOrExtendedBySalesOrPromotionalMaterials.TheAdviceAndStrategiesContainedHereinMayNotBeSuitableForEverySituation.ThisWorkIsSoldWithTheUnderstandingThatThePublisherIsNotEngagedInRenderingLegal,Accounting,OrOtherProfessionalServices.IfProfessionalAssistanceIsRequired,TheServicesOfACompetentProfessionalPersonShouldBeSought.NeitherThePublisherNorTheAuthorShallBeLiableForDamagesArisingHerefrom.TheFactThatAnOrganizationOrWebsiteIsReferredToInThisWorkAsACitationAnd/OrAPotentialSourceOfFurtherInformationDoesNotMeanThatTheAuthorOrThePublisherEndorsesTheInformationTheOrganizationOrWebsiteMayProvideOrRecommendationsItMayMake.Further,ReadersShouldBeAwareThatInternetWebsitesListedInThisWorkMayHaveChangedOrDisappearedBetweenWhenThisWorkWasWrittenAndWhenItIsRead.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norLearntoCodeProductions,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.
TABLEOFCONTENTSTableofContents
Chapter1.WhyYouShouldLearnProgramming
Chapter2.WhyPythonisthePerfectLanguage
Chapter3.GettingStarted:Pre-reqs
Chapter4.Variables,Expressions,Statement,Strings
Chapter5.Functions
Chapter6.Conditionals,FlowControl,Decisions
Chapter7.Iterations
Chapter8.Lists,Dictionaries,Tuples
Chapter9.ObjectOrientedProgramming
Chapter10.Classes,Objects,Inheritance
Chapter11.Debugging
Chapter12.Nextup
WHYTHISBOOK?
Theadage“penismightierthansword”isbestservedbyprogramminglanguages.Youliterallytypeandcommunicatesolutionstoproblemsonacomputer,anditcomestolife.
ThisbookintroducesPython,thesimplestandcurrentlyoneofthemostpowerfulObjectOrientedProgramminglanguagesontheplanet.ThebookshowshowitissimilartolearninganewdialectofEnglish,onemeantforthecomputingdevicesyouholdinyourhands.
ItwillintroduceyoutothebasicsofPythonlanguage:itsfundamentalbuildingblocks,theirsyntax,theirbasicuses,andhowtheyarerelatedtooneanotherincreatinglargercodes.
Thisbookismeantfornovicesandbeginners.Hence,itusessimplereallifeexamples,offersshortcodeswithexplanations,andcontinuouslylinksbacktoearlierchaptersandbuildsonthem.
CHAPTER1.WHYYOUSHOULDLEARNPROGRAMMING
Theriseofsmartdevices,wirelessconnectivity,andincreasedusermobilityinofficesmadecomputersanintegralpartofourlifestyles.Asourrelianceonsmartdevicesandvariousappstocompleteadiverserangeofactivitiesincreases,learningtocodeisbecomingakintolearningasecondlanguage.
Normally,welearnsecondlanguagestoincreaseourreach,overcomegeographicandculturalbarriers,andtobeabletocommunicatewithpeoplefromdiversecultures.Smartdeviceshavebroughtdownbarriersacrossdifferentcultures,andhavebecomeoneofourmosttrustedcompanions.However,wearenotabletoeffectivelycommunicateandinstructoursmartcompanionstoperformtheactionsthatwedesire.
Learningtoeffectivelycommunicatewithcomputersandsmartdevices,andbeingabletoinstructthemtoperformdifferenttasksisfastbecomingsomethingmorethananaddedskill—itisbecomingpartofwhatitmeanstobehumanintheageofDigitalNatives.
7REASONSFORLEARNINGTOPROGRAMLearntoprogramandyouwillbeabletoexperiencethefollowingseven,awe-inspiringrealitiesofbeingaDigitalNative.
IT’STHEONLYTIMEWHENWRITINGCANLITERALLYSOLVEPROBLEMSTheadage“penismightierthansword”isbestservedbyprogramminglanguages.Youliterallytypeandcommunicatesolutionstoaproblemonacomputer,anditcomestolife.
It’samazingtorealizehowpowerfulthisformofcommunicationis.MostofsmartphoneusershavevisitedAppStoresandseenarangeofapps,eachsolvingauniqueproblemforus.Knowingaprogramminglanguagemeansthatyoucanbreakaproblemintosmallerproblemsandcreateprogramsforyourselfandothers.Somanyproblems,nomatterhowtrivialcannowberesolvedsimplybywritingthemoutinaprogramminglanguage.
PROGRAMMINGTRANSFORMSYOURCOMPUTERANDSMARTPHONEINTOAPOWERHOUSEHumanslandedonthemoonrelyingoncomputingpoweratleasta1000timeslesspowerfulthanthecomputingpowerofoursmartphones.
By2016,over2billionpeoplewillbeusingsmartphonesacrosstheglobe.Justimaginewhatthisprocessingpowercanbeputtousefor.ImaginewhatyoucancreateanddeveloponyourPCforusewithyoursmartphones:personalizedapps,games,tools,andmore.
Thepossibilitiesareendless.
PROGRAMMINGSIMPLIFIESTASKSBYAUTOMATINGTHEMWeliveinaworldwhereefficiencyisthehallmarkofeverything.Nobodywantstoperformtediousandrepetitivetasksifyoucanpayforasolutionthatcanautomateit.Thisrangesfromofficetaskstopersonalones.
Bylearningtocode,youcancreatesimplescriptsthatsimplifytasks.ThinkofgeneratingmacrosinMicrosoftOffice(ExcelandWord)orscriptsthatsimplifytasksyouhavetoperformregularlyatworke.g.creatingfoldersforprojects,completingforms,creatingshortcuts,addingmorefeaturestoexistingsoftware,etc.
ITDEVELOPSYOURABILITYFORABSTRACTANDDISCIPLINEDTHINKINGInstructingcomputersrequiresthatgivethemstep-by-stepinstructionsthatlinkpre-determinedinputstoexpectedoutcomes.Tocommunicatetothecomputer,youhavetowriteinanexplicitlanguage,fromproblemtosolution.Thisrequiresbreakingdownabstractproblemsintosimplerones,andthenorganizingthemintoinputsandoutputs.
Programmingteachesyoutoorganizethoughtsandbreakdownaproblemintoconstituents,identifyingexternalfactorsandtriggers,andmappingastep-by-steprouteforcomputingtheinputsintooutputsi.e.intosimplerchunksofprogrammablecode.
Thistrainsyourmindtothinkclearlyandsystematically,filteringoutinformationthathasnobearingsonthesolution,andfindingthesimplestsolutiontotheproblem.
FUTUREJOBSWILLREQUIRESOFTWARESKILLCurrently,programmingmaybeaskilltoboastyourchancesofentryintothemarket,howeverasorganizationsfocusonincreasinginterdepartmentalcollaboration,theybegintopreferpeoplewithinter-disciplinaryskillsets.Inthelongrun,beingabletoprogramwillbecomeaskillneededtosurviveinthetechnologymarket.
BECAUSEIT’SNOTHARDTOLEARNIfyoucancomprehendEnglishlanguage,learningtoprogramissimplyamatteroflearningthelogicbehindprogrammingwords.Overtheyears,programminglanguageshavebecomemoreintuitive,utilizingcommandsthatclearlystatetheirpurposeandhenceallowyoutonearlyconstructsentences“If-Then”,“Else”,“Print”,“Switch”,arejustthemostcommonlyusedcommandsinprogramminglanguage.
Allyouhavetodoislearnthegrammar,andwithpracticeyouwillbeabletowritethoseshortessaysthatidentifytheproblem,itscomponentsandinputs,andtheoutputsforeachinput.
PROGRAMMINGHASGREATEARNINGPOTENTIALAsyougetbetteratprogramming,youcaneasilyleverageyourproblemsolvingskillstodevelopsoftwareforsale.Thisincludesworkingasafreelancer—buildingapps,developingcustomsoftware,creatinganddesigningwebsites,orhelpingclientscompletetasksusingexistingsoftwareandplatforms(MicrosoftExcelandWord,Flash,Java,etc.).
INCONCLUSION—PREPARETOLEARNProgrammingisanadd-ontoyourcurrentunderstandingoftheEnglishlanguage.Thinkofitasanewdialect,onethatyourcomputerandsmartdeviceunderstands,onethathasalotofbenefitsinthemodernworld,iseasytolearnandonethatwillsoonbecomeamusthavefordigitalnatives.
CHAPTER2.WHYPYTHONISTHEPERFECTLANGUAGE
Inanagewheremachinesarebecominghighlyintelligentandarecontinuouslysimplifyinghuman-machineinteractions,itonlymakessensetouseanintelligentprogramminglanguage.
ExistingstaticallytypedlanguagessuchasPascal,C,orothersubsetsofC++andJavaintroduceverbosesyntaxthatcloudtheactualprocessofproblemdecompositionanddesignofdatatypesthathavetobeprogrammed.
Hence,forsomeonewhodoesnotknowhowtocode,theselanguagesseemunnatural.Furthermore,theadditionalcomplexityofthesyntaxonlyslowsdownthepaceofingrainingthemethodologyofprogramming.
ThisiswherePythonbringsinthepowerofsimpleandconsistentsyntax,backedbyalargestandardlibrarywithrealproblems.
NotwithstandingtheriseinitspopularityinAmericancollegesasreportedbytheAssociationforComputingMachinery,PythonhaseffectivelyreplacedJavaasthefirstlanguageofchoiceforbuddingprogrammers.
SowhatismakingPythontheperfectlanguageaftertwodecadesofbeinginthefield?
#1—MINIMALSETUPInstallingandrunningPythonisextremelysimple.AllyouhavetodoisdownloadthefileandeitherrunitthroughtheTerminalprogram(forMac),orthePowerShellprogram(Windows),andLoandbehold!You’rerunningPython.
#2—WRITINGAPROGRAMISAKINTOWRITINGINENGLISH!Pythonisauniversallanguage.Thismeansthatitssyntaxandcodinglingoisexceptionallysimplifiedandeasy.
PythonistheclosestthingtowritingalogicalargumentinEnglish.Thecommandsaresimpleandtheadditionalbaggageofgrammar(programmingsyntaxsuchasbrackets,colons,quotes,etc)isminimal.Yougrasphowtosystematicallybreakdownaproblemintosimplersteps,andyoucaneasilycodeitinPython.
Inaphrase:agreatfirstexperienceforanybeginner.
Thestandardfirsthands-onprogrammingexperiencethatallbeginnersgothroughistoprintsomethingonthescreenusingcoding.Thisisnormallythewords“HelloWorld”,amongothers.
Pythonmakesitliterallyamatterofwritingasentence
print(“HelloWorld”)
Comparethistothefollowing(Java):
publicclassHelloWorld{
publicstaticvoidmain(String[]args){
System.out.println(“Hello,World”);
}
}
Furthermore,whenyoumoveaheadintothecourse,otherexamplesofsimplifiedprogrammingwillleapout,includingsimplereading/writingofinformation,stringprocessing,GUI’s,websitecode,Databases,websites,etc.
Itssimplicityandeaseofprogrammingisthereasonwhyithasbeenadoptedbysomanypeopleandforsuchawiderangeoftasks.Thisisfurthermadeenjoyablebythefactthataverylargecommunityofenthusiasticdevelopersisalwaysabuzztoaidnewcomersbecomeinitiatedintothefold.
#3—PYTHONISEASYTOREADPythonisdesignedtobeaneasyread.
“Readability”ofacodemayandseemunimportantrightnow,butitbecomesthedefiningfactorwhenthecodebecomeslargerandmorecomplex.
Readabilityisveryimportant,becauseunlikeacoursebook,thechapters(orchunksofcode)arenotalwaysarrangedtoworkinastep-by-steporlinearorder.Attimescodingblocksinthefarrecessesofthecodeneedtobecalledearlier,orlater,multipletimesthroughoutthecode,andsoon.
Easeofreadabilityisimportantforsharingacodebetweenateam,fortroubleshootingaprogram,andformakingchangestoit.Intraditionallanguages,readingbecomesincreasinglydifficultasbecauseofallthenon-Englishgrammaticalsyntax.
Pythonusesindentationtogivestructuretothecode,andthoughprogrammerswhoaremigratingfromadifferentlanguagetoPythonmaybeheardcomplainingaboutthelack(andnearabsence)ofbraces,itisoneofthekeybenefitsofPython:itsimplyde-clutterstheworkenvironment!
Thinkofindentationsliketheheadingsinyourwordprocessingsoftware(H1,H2,H3,H4,H5,andsoon).Incodingtheheadingsarenormallycurlybrackets(“{}”)thathavetobeaddedatthestartandendoftheparagraph.
Asaresult,twotypesofcommunicationarehappeningsimultaneously:bracestotellthemachineabouttheprogram,andtheindentationstotellthereader(anotherprogrammer)whattheprogramisabout.
NowimagineNOThavingtoaddbracketsandindentationandfollowalegendyouhavecreatedearliertokeepyourprogramreadable.Pythondoesthisbyofferingasinglestructuretodenoteaprogram:makingiteasierforhumansandcomputersaliketoreaditwithease.
#4—YOUDONOTHAVETOCOMPILETHEPROGRAMTORUNITWhenyou’relearningsomethingnew,mistakesareboundtohappen.Howthosemistakesareshowntoyouoftenplaysacrucialroleinhowmotivatedyouaretotryagain,orhowaffectedyouarebythemistakethatyouhavemade.WithPython,allerrorsareidentifiedatruntimeinsteadofshowingafailuretocompileerror.Thismakesiteasiertoidentifyandfixmistakesimmediately.
Thisisincrediblyusefulwhenyouwillbedesigningacomplexalgorithmwherechangesaremadecontinuously.Whereotherprogramminglanguageswillwastetimetakingyouthroughthecompile-run-debugcycle,Pythonsimplyshowstheresult(ortheproblem)inthesameinterpreter.
Hence,youcanmakeinnumerablechangestoapieceofcodeandexecuteitinreal-timeintheinterpreter.Thisbooststhelearningprocessasyoucanconsciouslymakeerrors,seeitsimpact,andtroubleshoottheprogram.Thisdramaticallyreducesthedevelopmentcycle,andbecomesespeciallyusefulforrapidprototypingofyourcode.
#5—PYTHONISOPEN
Pythonisanopenontwoaccounts:
1)Opensourceasprogramminglanguage
2)BuiltusingOpenobjects
Asanopensourceplatform,itsliberaldistributionlicenseallowsthelanguagetobeusedforcodingprograms/appsthatcanseamlesslybeintegratedasanextensionofotherproprietylanguages.
Intermsofcodingarchitecture,Pythonisgreatatintrospectionbecausethecodeisbasedondiscretechunksofprograms(knownasobjects).Wewillgettechnicallater,butforthemoment“beingopen”meansthatitwillbereallyhardforyoutowritedirtycodeorsidesteppropercodingmethodstosolveproblems.
Hence,Pythonforcesyoutowritebettercodefromthebeginning,andthisprovesveryhelpfulduringdebugging.
CHAPTER3.GETTINGSTARTED:PRE-REQS
ThereareonlytwoprerequisitesforgettingstartedwithinstallingandusingPython:
Reasonableknowledgeofusingacomputerandinternet.Acompellingdesireforlearninganewlanguageforcommunicatingwithcomputers.
INSTALLINGPYTHONONWINDOWS
DownloadthelatestversionofPythonfromtheofficialWebsite.[LINK]
NOTE:Twoversionsofthelanguageareavailable,Python2.xandPython3.xThedifference,inallitssimplicityisthatPython2.xislegacyi.e.itistheonethathasbeeninstalledonmostdevicesandhenceisthecurrentnormforPython,whereas,Python3.xisthepresentandfutureofthelanguage.
TheWindowsversionisdownloadedasanMSIpackage,andcanbeinstalledwithadouble-clickontheopenshellfile.
AllowthewizardtoinstallPythontothedefaultdirectory:
ForPython3.xitwillbeC:\Python3x\—(xbeingreplacedbytheversionyou’vedownloaded,thelatestbeing2.7)
NOTE:ThedifferentfoldersmeanthatyoucaninstallmultipleversionsofPythononthesamesystemwithoutcausinganyconflicts.
However,asingleinterpreteractsasthedefaultapplicationforPythonfiletypes.
That’sit.
YoucanusePython;however,itisrecommendedthatyouinstallthelibrariesandtoolsdescribednextbeforeworkingonwritingyourcode.Inparticular,Setuptoolsisamustinstallasitallowsyoutoeasilyuseotherthird-partyPythonlibraries.
SETUPTOOLS+PIPFromalltheSetuptools,thisisthemostcrucialthird-partyPythonsoftwarebecauseitextendsthecapabilitiesofthepackagingandinstallationfacilities(offeredinthedistutilspresentinthestandardlibrary).
OncetheSetuptoolsisaddedtoyourPythonsystemanddirectory,allPythoncompliantthird-partysoftwarecanbeaddedusingasinglecommand.Furthermore,withtheSetuptoolsinstalled,youcanaddanetworkinstallationcapabilitytothesoftwarethatyoucreate.
Python3,generally,comesequippedwithPIP.YoucandownloadthelatestversionoftheSetuptoolsforWindowsHERE.
NowinstallPIP,areplacementforthePythoncommandeasy_installandwhichintroducesun-installationofdifferentpackages.
VIRTUALENVIRONMENTSNext,youhavetoinstallaVirtualEnvironment,virtualenv,atooltokeepeachproject
self-containedandseparatefromoneanother.Thinkofitthisway:whenyouwriteacode,itleveragesthePythonworkenvironmenttoreduceitssize(e.g.usingsomepre-madefunctionsfromthePythonlibrary).Hence,whenitissaved,onlytheessentialinformationneededforthesavedfiletobereopenedandruninthePythonworkenvironment.
Nowyoucreateanothercodeandsaveit.
NowthenewprojectmayusedifferentlibraryobjectsfromPython,however,unlessamechanismexiststokeeptheirrelianceseparatefromoneanother,oneprogramcaneasilyconflictwiththeother.
Avirtualenvironmentseparatesalldependenciesrequiredbydifferentprojectsinseparateplaces.Hence,eachprogramcansafelyruninitsownsafehaven.
DownloaditfromHERE.
THESECONDPREREQUISITEAstrongdesiretolearnhowtowritecomputerprograms.
Ifyoudon’tknowhowtoprogramandarenewofPython,thenunderstandthataswithanynewlanguage,ittakestime,practice,andperseveranceinfaceofmistakesandsmallfailures.Hence,youmusthaveastrongdesiretolearnthelanguagetosucceed.
STRONGDESIRETOLEARNPythonrequiresfocusedeffortinlearningthebasics,learninganewmethodforlogicallybreakingdownaproblemintoconstituentparts,learninganewprogrammingmethodology(Pythonisanobjectorientedprogramminglanguage),andpracticingcodingbehaviorinanewcodingenvironment.
Don’texpectamiracletohappen.
Youwon’tlearnitbysimplyreachingtheendofthisbook.
Aswithanylanguage(spokenorcoded),practiceandexperiencematteralot.Simplyreadingandmemorizingsyntaxwillnotbringamiraculoustransformationandmakeyouanaptprogrammerinthefield.
Unlessyouarewilledbyatruedesiretolearnthenewlanguage,learningtoprogramcanbecomeboring,mistakeswillcompoundasade-motivatingfactor,andyouwillnotingrainanewanalyticprocessofbreakingdownproblemsandwritingsolutions.
PRACTICE,MOREPRACTICE,ANDEVENMOREPRACTICEAlllanguagesarelearnedbyrepetitionandexperimentation.
Youhavetolearnhowtoputtogetherphrasesandcreatemeaningfulsentencesoutofthem.WithPython,itisaboutusingthesyntaxandcommandstocreatechunksofcodethatcanperformanaction(takeinput,compute,displayanoutput,etc.),anddosoefficiently.
Thisbookwillofferyouthebasicsofthelanguage,butyoumustwillyourselftoputyourbraininhighgearandwriteALOTofcodefordifferentproblems.Onlythenwilltheinformationthatissharedinthisbookwillstickwithyou.
Thinkofthethingsyouhavebecomegoodatovertheyears:talking,surfing,gaming,playingmusic,generalknowledgeaboutfashion,writinggoodessays,humor,andmore.Allofthemneededtobepracticedagainandagaintogainsufficientcommandandconfidenceinyouabilities.
ProgrammingwithPythonisquitesimilartothatexperience.
CHAPTER4.VARIABLES,EXPRESSIONS,STATEMENT,STRINGS
RememberthoseEnglishgrammarlessons?How“eachsentence”ismadeofasubjectandanobject,hasnouns,pronouns,auxiliaryverbs,andadjectives,andthelike?
Justrememberhowwordsandauxiliaryverbswereusedtocreatesentences,andhowthesesentencesareusedtocommunicatemorecomplexthoughts.
Thisiswhatwearegoingtodohere.
Python(andmostotherprogramminglanguages)aremadeofsomeuniversalbasiccomponents.Theseinclude(inorderofincreasingcomplexity)variables,expressions,statements,andstrings.
Thenamesareself-explanatory.Let’sseethemindetail.
VARIABLE
Avariableisthe“x”youtriedtofindinmostofyourmathclasses.Inprogrammingitisadatatypecapableofcontainingchangeablevalues.
Theabilitytomanipulatevariableinaprogramminglanguageisoneofthemostpowerfulfeaturesinthecodingworld.
Hence,wemustbeginbyunderstanding“values”inPython.
VALUESANDDATATYPESValuesarecategorizedaccordingtothetypeofdatatheycanhandle.Forexample,“Hello,Programming!”,“2”,and“2.3”areallconsideredvaluesinPython,excepteachbelongstoadifferentcategoryordifferentdatatype.
NOTE:Datatypedonatesthedifferenttypesofdatathatcanbeusede.g.characters,numbers,floatpoint(decimalnumbers),etc.
Thenumeric2isanintegerbecauseitcontainsawholenumber,whereasthe“Hello,Programming!”isastringbecauseitcontainsastringofletters,and“2.3”isafloatbecauseithasdecimalnumber.YourPythoninterpreterisabletoidentifyandusestringsasasinglevalueenclosedwithinthequotationmarks.
Ifinconfusionaboutthetype,letPythontellyouthedatatypeofyourvaluewiththetype()command:
>>>type(“Hello,Programming!”)
<type‘str’>
>>>type(13)
<type‘int’>
Notethatthestringsarealwayscontainedwithinquotes“”.Hence,ifyouweretoputnumericvalueswithinthesequotes,theyautomaticallybecomestrings.
>>>type(“13”)
<type‘str’>
Furthermore,whenwritingstrings,avoidusingcommastoseparatetens,hundreds,andthousands.Forexample,ifyouwanttowritetwohundredthousandas2,00,000,Pythonwouldreactasfollows:>>>print(2,000,000)
200
Unexpectedright?
That’sbecausecommasareinterpretedbyPythonasseparators.Hence,youseethreevalues:2,0,and0.
NOTE:Thesyntaxforprintisprint(x)with‘x’beingreplacedbystrings(“string”)ornormalnumericvalue(2)
ThisisdifferentfromPython2,wherethesyntaxissimply:printx,print2,orprint“this”
Othertypesincludefloat(fordecimalplaces)
>>>type(13.1)
<type‘float’>
>>>type(“13.1”)
<type‘str’>
NOTE:Youcanuseboth,single(‘’)anddouble(“”)quotesforwritingstringsinPython.AND,youcanusedoublequoteswithinsinglequotes.Forexample:(‘Hesaid,“Loandbehold!”‘)
Let’sstartwithvariables.
VARIABLESRememberhowbasicequationswerecreatedinmath?
Question:IfSamboughttwoeBooksfor$3,howmuchwillitcosttopurchase5eBooks?Wenormallybeganwithsupposing“x”asthecostof5eBooks.
Oncesupposed,“x”canbeusedanywhereinthesolutionandanyonecaneasilyfigure(interpret)that“x”isreferringtothe“Costof5eBooks”definedinthebeginning.
Inprogramming,avariableisthenamethatreferstoachangeablevalue—onethatcanbechangedandautomaticallyupdatedatwill.
Likemath,variableshavetobedeclared/created(supposed)andthenassignedavalue.Inpython,thevalueofavariableisassignedusingtheassignmentstatement:>>>message=“I’mprogrammingwithPython!”
>>>x=2015
>>>yr=365.25
Noticehoweachtypeofdataisassignedinasimilarmanner,startingwithastring,aninteger,andafloatingpointnumber.Themostimportantthingistheequalsign“=”thatseparatesthenameofthevariable(lefthandside)fromthevalueofthevariable(righthandside).Theequalsign“=”isknownastheassignmentoperator.
Theleft-hand,right-handdivideisarule.Deviationisnotpermitted.Ifyoureversetheorder,itbecomesmeaninglessfortheinterpreter.
Hence,thefollowingmakesnosense.>>>“I’mprogrammingwithPython!”=message
>>>2015=x
>>>365.25=yr
TYPESOFVARIABLESVariablesalsohavetypes.Intheexampleabove,the message isastring, ‘x’ isaninteger,and ‘yr’ isafloat.
Youcanverifythetypeofthevariableusing type().>>>type(message)
<type‘str’>
>>>type(x)
<type‘int’>
>>>type(yr)
<type‘float’>
Notehowthetypeofthevariablecorrespondstothetypeofthevalueitcontains.
NAMINGYOURVARIABLES,THEILLEGALITIESCertainnamingconventionsareusedwhennamingvariables.Thesearesimplystandardsthatareusedtostandardizehowcodeiswrittenandtokeepitclean.Thisgainsimportanceasyourcodegetslongerandyourvariablesbecomemoredescriptive.
Additionally,certainpythonruleslimithowyourvariablecanbeassigned.Yourvariablemust:
1. Alwaysbeginwithanalphabet/letter2. Neveruseillegalcharacters($,&,*,etc.)3. NeveruseaPythonkeyword
Therefore,thefollowingwillresultinsyntaxerrors:>>>14numbers=“Whatarethosefourteennumbers?”
SyntaxError:invalidsyntax
>>>Increase$=985
SyntaxError:invalidsyntax
>>>class=“PythonBasics“
SyntaxError:invalidsyntax
Now “class” isaPythonkeyword,whichmeansitispartofitsrulesandstructure.
Pythonhasthirty-onesuchkeywords:
raise while return try with print
is or lambda not pass
for if from global import
del except elif else exec
as class assert break continue
yield and def finally in
Keepthistablehandy,andiftheinterpretercomplainsaboutsyntaxerror,checkyourvariablenaming!
STATEMENTS
Likenormallanguage,astatementisaninstruction.InPython,youcanexecuteprimarilytwokindsofstatements:print and assignment .Theformerproducesavaluewhilethelaterdoesnothing.
Whenyouwriteastatement,theinterpreterexecutesitandtriestodisplayresults:print(3)
t=17
print(t)
Theabovecodewillproducetheoutput:3
17
Theassignmentstatementusedforcreatingavariableproducesnooutput.
EXPRESSIONSAsinlanguage,anexpressionisacompletethought,withapremiseandaconclusion.Inpython,anexpressionhasinputs,adefined/expecteduseofthoseinputs,andanexpectedwayofeitherdirectlydisplayinganoutputorcomputingittodisplayanoutput.
Generally,meaningfulexpressionsareacombinationofvariables,values,statements,andoperatorsthatforcestheinterpretertoevaluateitanddisplayresults:>>>1+1
2
AvalueandavariableitselfaresimpleexpressionsinPython:>>>2015
2015
>>>t
17
However,theseexpressionssimplyprint/displaytheexpression.Evaluatinganexpressionisnotsimilartosimplyprintingavalue.
Taketheexample:>>>message=“Writingexpressions?”
>>>message
“Writingexpressions?”
Noticehowthequotationmarksaredisplayedintheoutput.However,whenusing print() ,onlythecontentsofthestringaredisplayed:>>>print(message)
Writingexpressions?
Thisisbecausethe print() statementfetchesthevalueofthevariable(thestring).
Now,anexpressionallbyitselfisalegalstatement.Youcanwriteasmanyasyouwant,butunlessyouusecertainoperatorsandcommandstocommunicatethepurposeoftheexpression,NOOUTPUTwillbedisplayed.Forinstance:2015
365.25
“Python,Expressions!”
13+1
Nooutputwillbedisplayed.
Thisiswhereoperatorsandoperandscomeintoplay.
OPERATORSANDOPERANDSAcodeissupposedtoperformcertaincomputationsontheexpressionstogeneratepredictableoutputs.Computationsareperformedusingoperators—specialsymbols
whichyoumaythinkofasshortformsfordifferentcommands.
Thevaluethattheoperatorusesiscalledanoperand.Herearesomeexamples:
1+2+3
t-20
t*30+minutes
t/60
(1+2+3)*(6-2)
Howthesymbolshavebeenused+,-,/,*(formultiplication)arethesamewaytheyareusedinmathematics.Now,whenavariableisusedwithoperator(s)tocreateanexpression,theinterpreterfetchesandcomputesthevalueassignedtothatvariable.
However,thereisacaveat.Thoughaddition,multiplication,subtraction,andexponentiation(representedbythedoubleasteriskoperator**)haveasingleuseandgenerateanexpectedresult,divisiondoesnot.
Let’ssaythefollowingexpressionisused:>>>t=49
>>>t/60
0.8166
Butwhatifwantedtoperformanintegerdivisionwheretheanswerisalwaysroundedofftotheclosestintegervalue?
Let’ssay:>>>t=121
Thisiswhere“//”isusedtoindicateourintention>>>t/60
>>>t//60
2.0166
2
Anotherwayofovercomingistoassigndatatypestotheanswer(afloat),butwewillcometothatlater.
ORDEROFOPERATIONSYoucanusemultipleoperatorsinasingleexpression;howevertheirevaluationisdependedontherulesofprecedence.
Pythonfollowsthesameruleasisappliedformathematicaloperators.RememberPEMDAS tomemorizetheorder :
Parentheses—Expressionsintheparenthesisarealwaysevaluatedfirst.Hence, 3*(4-1) is9.Parenthesisarealsoagreatwayformakingiteasiertoread
theexpressionsuchas (t*100)/60 .Exponentiation—(**)hasthenexthighestprecedence.Hence, 3**1+1 is4andnot9,whereas 4*1**3 is4andnot64.MultiplicationandDivision—Bothhavethesameprecedence,albeithigherthanadditionandsubtractionAdditionandSubtraction—Alsohavethesameprecedence,albeitlowerthanmultiplicationanddivision.
Whatifmultiplicationanddivisioncomeinthesameexpression?
Forexample: t*100/60
Operatorsthathavethesameprecedenceareevaluatedfromtheirappearancefromlefttoright.Hence,intheexpression t*100/60 ,multiplicationhappensfirst,followedbydivision.
OPERATIONSANDSTRINGSGenerally,youcannotperformanymathematicaloperationsonstrings.Thisincludesinstanceswherethestringslooklikenumbers,oronlyhavenumbersinthem.Thefollowingexampleshowsanillegalmathematicaloperationonasetofstrings:
message-1“Word”/2015message*“Now”“2012”+3
Thoughmathematicaloperationscannotbeperformedalgebraically(orasweareaccustomedto)onstrings,someoperatorscanworkwiththem,butinadifferentmanner.
Forexample,the“+”operatorwhenusedwithstringsperformsconcatenationinsteadofaddition.Itmeansthatthetwostrings(oroperands)arelinkedend-to-endi.e.theyareattachedoneaftertheother:
Subject=“Python”
Object=“ProgrammingLanguage”
Aux_Verb=“isa”
Adj=“simple”
print(Subject+Aux_Verb+Adj+Object)
Theoutputofthiscodewillbeprogram PythonisasimpleProgrammingLanguage .Thespacesbeforethewordsinthestringarepartofstring,andnecessarytoproducethegrammaticallycorrectspacingbetweentheconcatenatedstrings.
Themultiplicationoperator(*)alsoworksonstrings.Itsfunctionistoperformrepetitionsonthatstring.So,forexample,theoperations:
‘Why?’*3
Willproducetheresults‘Why?Why?Why?’
Inmultiplication’s(*)case,oneoftheoperandsmustbeanintegerwhiletheotherastring.
CHAPTER5.FUNCTIONS
Let’sdelveintopurposefulprogrammingwheretheprogramwilldemanduserinputtoexecuteacommandortoperformatask.
Thisisachievedusingfunctions.
Let’stakeareallifeexamplesayyouwanttosurpriseafriendontheirbirthday.Youinformotherfriends,gatheragroup,andtellthemhowthepartywillgo.Forexample,youdecideonasignalatwhichtheywillturnonthelights,blowthetrumpets,orsingthebirthdaysong.Inthisscenario,youhavecreatedabasicplanofactionandasignal(aninput)andhoweveryone(individually)willreacttoit.
Youarenotexpectingtotelleveryonewhattodoagainwhenyougivethemthesignal,BECAUSEyouhavealreadydefineddifferentfunctionsandassociatedsignalsthatwillactivatethem.
InPython,functionsaresmallerindependentpiecesofcodeinyourprogram.Theyallowyoutodivideandorderyourcode,andhencemakeitcompact,moreorganized,andreadable.Oncecreated,afunctioncanbeusedatanytime,andanynumberoftimesanywhereinyourprogram.
USINGAFUNCTIONPythonhasalibraryfullofpre-madefunctionsforvariouscommontasks.Youcanusethembysimplycallingthem,andgivingthemaninput.
“Calling”afunctionsimplymeansusingthefunctionname(andnotcopyingthewholecodeagain),andgivingthefunctionaninputitcancompute.
Thinkofitlikecallingthemoversortheletterman.Theyknowtheirfunction,andifyougivethemtherightinput(i.e.thingstobemovedoraletter/parcel),thenyouwouldnothavetoexplainittothemwhattodowiththatinput.Theywillcompletethejobonceyougivethemtherightinput.
InPython,callingafunctionissimple.Defineaparameternameanditsworkingparameters:
function_name(parameters)
Simple,right?
Let’sunderstandthedetailsofthesyntaxshownabove:
Function_Nameidentifieswhichfunctionitisyouwanttouse.Youwillfigureitoutyourself,asinthepreviousanalogy,ifyouwanttomovesomethingyou’dcallthemoversandalettermanifit’sasmallparcel/letter.Asanexample,abasicfunctionistheraw_inputfunction.We’lluseitsoon.Parametersarethevaluesortheinputsthatyoupasstothefunction.Thisvaluewillinformthefunctionwhatandhowitshoulduseit.Forexample,ifyouhaveafunctionthat addedavaluetoanumberaftermultiplyingitby3thentheparameterswillbe1)thenumberitshouldmultiplyby3,and2)thenumberitshouldaddtothisresult.Soifyouput5and2intheparametersforthisfunctionthenitwillfirstmultiply(5x3)andthenadd2(15+2),givingyou17
PARAMETERSANDRETURNEDVALUESNow,functionsnormallyworkinthebackgroundandwillnormallynotshowtheresultofthecomputationtheyhaveperformedontheparametersyouhavegiventhem.
Returningthevalueorresultofitscomputationisimportanttoknowwheretheprogramis,orifitisgeneratingtheexpectedresults.Whatifyouhavegivenitaletteroranillegalsymbol($,%,#)insteadofanumber?
Sohowdoesafunctionshowwhatitdoes,orhasdoneontheterminal?
Let’sseehowthecomputerseesthefunction.Itdoesnotseethenameofthefunction(orincaseofavariable,thevariable’sname),rather,itonlyseesthefinalvaluethatthefunctionorthevariablehasstoredinit.
Hence,incaseofthefunction,thecomputerseesthefinal,endresult.
Let’staketheexampleofafunctionmultiply() thatmultipliesanynumberby7.So,itsinputisanynumberyoucanthinkofandplaceitinthebrackets,thefunctionmultipliesit
by7.
NOTE:multiply()isnotapre-madefunctioninPython.Youcan’tuseitstraightoutasmentionedhere.
Soifyoutypedthis:
t=multiply(60)
Itwillappeartothecomputerasthis:
t=420
Thefunctionranitself,andreturnedanumbertothemainprogram,usingtheparameterswehadgiven.
Let’stryarealfunction,input .
NOTE:PreviousversionsofPython(<Python3)usedraw_inputinstead.
Thefollowingfunctionaskstheusertoenteravaluethatitturnsintoastringoftext.Forexample:
#thefirstlinemakes“t”equaltothevaluethatyoutypeinonthescreen
t=input(“Typesomething,andIshalldisplayitonthescreenagain:”)
#Thenextlinewillprint,orreturnthevaluethatyouhaveenteredin‘t’.Itwillshowtheresultofthefunction
print(t)
Theresultissimplythecontentthatyouhaveenteredonthescreenaftertheprogramisrun.
NOTE:‘#’isusedforwritingcommentsinthecode.Anylinethatbeginswith“#”isnotcomputedbythePythoninterpreter.
Thinkofcommentingasyourin-programdocumentation,informingorremindingyouaboutwhateachchunkofcode/functiondoes.
Itbecomescrucialasyourcodebecomeslargerandmorecomplex.Practiceitfromthebeginning .
So,ifyoutypein“Really?”intheaboveprogramwhenaskedtodoso,thecomputerseesthefunctionas:
t=“Really?”
print(“Really?”)
Remember,thattothecomputer,variableisjustastoredvalue.Itdoesnotappearas‘t’.Soisthecasewithfunctions.Theydon’tappearasthewholecode,onlythevaluetheycontaininthem.
DEFININGYOUROWNFUNCTIONSYoucancreateyourownfunctionsusingthe‘ def ’operator.
Thinkofafunction,andwhatitwilldo.Nownameit,anduse‘ def ’asfollows:
deffunction_name(parameter_1,parameter_2):
#noticethecolon“:”attheendoftheline?#itisanimportantpartofthesyntax.Always#additattheendoflinethatstartswith#‘def’
{thisisthecodeinthefunction}
{morecode}
return{valuetoreturntothemainprogram}
Recallthattothecomputer,thevariableinthefunctionlookslikethevaluethatisstoredinsideitandthatfunctionsaresimilarandonlythevaluethattheyreturnisseenbythecomputer.
Itdoesnotmatterhowlargeyourfunction’scodeis.Onlythevaluematters.Becausethefunctionisaseparate,self-containedprogram,itdoesn’tseeanyofthevariablesinyourmainprogram.
Whythestressonwhatthecomputersees?
Hereisanexampletoshowtheimportance.Thefollowingfunction‘written()’willprinttheword“Functionsareindependentofthemainprogram”onthescreen,followedbyreturninganumber“54321”tothemainprogram.
#creatingthefunction
defwritten():
print(”Functionsareindependentofthemainprogram“)
return54321
#howtousethefunction
written()
Thelastlineofcodeiscallingthefunction.Whenyoutypethat,thefunction’svaluesaredisplayedonthescreenandnotthecompletefunction:
Functionsareindependentofthemainprogram
54321
Sowhathappened?
Assoonasthe defwritten() wasrun,Pythoncreatedafunctionandlabeledit‘written’
Whenthewritten() wasrun,Pythonexecutedthefunction‘written’thatithadpreviouslycreated.Runningthefunctionmeantexecutingalllinesofcodewithinin.
Thefunctionfirstprinted“Functionsareindependentofthemainprogram” andthenreturnedthenumber‘ 54321 ‘backtothemainprogram.
Asaresult,themainprogramonlyseesthelineas‘print54321’andsodisplays‘54321’inthenextline.Yourfunctiondidnotknowthatthestring “Functionsareindependentofthemainprogram” hadbeenprintedalready,allitsawwasthatitreceivedanewvalue‘54321’andprintedthatonscreen.
Functionscanalsoreceiveargumentsi.e.youcanpassvariablestothem.Forexample:
defa_function_with_args(username,message):
print(“Welcome,%s,Iamyournewfunction.Iwishyou%s”%(username,message))
Functionscanalsoreturnvalues.
Functionsmayreturnavaluetothecaller,usingthekeyword—‘return’asusedinthepreviousexample.Anotherexample:
defadd_both_numbers(a,b):
returna+b
CHAPTER6.CONDITIONALS,FLOWCONTROL,DECISIONS
Usefulprogramsareabletomakedecisionsbasedontheinputs.Thisisachievedbygivingthemtheabilitytochangethebehaviororflowoftheprogrambasedontheinputs.Thisisdoneusingconditionalstatements.
Theflowofthecodeistheorderofthecodeyouhavewritten.Recallthebirthdayexample.Youmayhaveplannedthatthehallwaylightswillgoupfirst,followedbythefriendsonthestairwayssingingthesongs,someonecomingwiththecake,etc.
Butdifferentinputs(orreactionsbyyourfriends)theflowofthepartymighthavetochange.
Incoding,normally,whenthecodeisexecuted,theinterpreterreadsitlinebyline,movingfromthetoptothebottom.However,attimesyoumayneedtoexecuteafunctionthatbegins40linesahead.Themosteffectivewayofincreasingefficiencyoftheprogramistobreaktheflowandimmediatelybringtheinterpretertothefunctionandexecuteit.
Whenthereisaneedtobreakthecodeandexecuteadifferentblockofcodealtogethertocompleteatask,conditionalscomein.
ConditionalscanbedividedintobasicconditionsandtheIfconditions,including:
If-StatementIf-ElseStatement
Let’stakethemonebyone.
BASICCONDITIONSTheseincludeallthearithmeticcomparisons,suchaslessthan(<),greaterthan(>),equal(=).Forexample:
3<4
3>2
t=5
t>7
AlloftheabovehaveBooleanresultsi.e.theyareeithertrueorfalse.Theseconditionscanbeusedtocontroltheflowoftheprogramusingconditionalstatements.
However,notallarithmeticdecisionaretransferredexactlytoPython:
Greaterthan > >
Lessthan < <
Greaterthanorequal ≥ >=
Lessthanorequal ≤ <=
Equals = ==
Notequal ≠ !=
CONTROLFLOWWITHTHEIF-STATEMENTWearewritingacodeforamovingcompanythatoffersflatratesforallitemslessthan60kg,whereasanythinggreaterthanthatischarged$20extra.Ourcodewillusedwiththeirweighingmachinetoinformthecustomeroftheextracharges.Here’sanexamplecode:
weight=float(input(“Pleaseentertheweightofyourluggage(inKg):”))
ifweight>60:
print(“Thisexceedsour60Kgflat-ratelimit.Anadditional$20isappliedforheavierluggagelikethis.”)
print(“Thankyouforyourbusiness.”)
Noticetheindentationbeforethefirst print command.ThisindentationtellsPythonwhattodowhenthestatementweigh>60istrueorfalse:
Whentheweightisgreaterthan60kg,itprintsadditionalcharges,andWhenitisnottrue(weight<60),itthanksthecustomer.
Thesyntaxfortheif-statementis:
ifcondition:
Indentedcode/statement
#thecolonispartofthesyntax.
Whatifyouwanttoexecuteseparatecodesforboth,TrueandFalseconditions?If-elsestatementisusedforthataswellusingtheif-elsestatement.
CONTROLFLOWWITHIF-ELSESTATEMENTThegeneralsyntaxforif-elsestatementsinPythonis:
ifcondition:
IndentedcodeifconditionisTrue
else:
IndentedcodeifconditionisFalse
Theindentedblockscanhaveanynumberoffurtherstatementsinsidethem.Forexample:
time=float(input(‘Howlongdidyourun?’))
iftime>20:
print(‘Goodwork!Let’scontinuemaintainingourhealth’)
else:
print(‘Goodeffort.Let’strytohitourtargettomorrow!’)
print(‘ExerciseforHealthyLiving’)
Theif-elsestatementislimitedtotestingasingleconditionandcontroltheflowusingonlytworesults(True/False).Multipletestscanbeincludedusingthe if-elifstatement .
CONTROLLINGFLOWUSINGIF-ELIFSTATEMENTSWhynotusetheif-elsestatementrepeatedlyincaseofmultipletests?Let’staketheexampleofgradeassigner:defGradeAssign(score):
ifscore>=85:
assign=‘A’
else:#ifnotAthenmaybeB,C,DorF?
ifscore>=75:
assign=‘B’
else:#ifnotAthenmaybeC,DorF?
ifscore>=65:
assign=‘C’
else:#grademustDorF
ifscore>=60:
assign=‘D’
else:
assign=‘F’
returnassign
Noticethenumberofindentations.
Asyourcodegrowslonger,thiswillbecomeproblematic.Seehowif-eliftransformsit:defGradeAssign(score):
ifscore>=85:
letter=‘A’
elifscore>=75:
letter=‘B’
elifscore>=65:
letter=‘C’
elifscore>=60:
letter=‘D’
else:
letter=‘F’
returnletter
NESTEDSTATEMENTSYourcodecanhavestatementswithinstatementsaswell:
ift>60:
Indentedstatement#1
else:
ift<30:
Anotherindentedstatement#2
else:
Indentedstatement#3
Asyourprogramgrows,nestingstatementswillincreasethedecision-makingabilityofyourcode.
CHAPTER7.ITERATIONS
Programsareusedtoautomateandsimplifyproblems.Thisrequiresrepeatingtasks,e.g.askingforinputmultipletimeswhenatableneedstobefilled.Thisiscalledaniterationofthesametask.Theyrequiretheinterpretertoexecutethesameblockofcodemultipletimes.
However,thisisnotpossiblewithhowtheinterpreternormallyworksi.e.sequentiallybymovingfromoneblockofcodetothenext.
Thisiswhereloopstatementscomeintoplay.
Theyallowustoexecutethesameblockofcodeasmanyasisneededtocompletethetask.
Therearetwomainloops:the WhileLoop andthe ForLoop .
Bothloopsrelyonupdatingvariables.Sofarwehaveonlycreatedandusedvariables,withoutchangingandupdatingtheoriginalvalueofthevariableduringexecution.Here’sanexampleofupdatingvariables:
a=1
b=a+2
b=2*b
a=b-a
print(a,b)
Theprogramisexecutedstep-by-step,toptobottom.Here’showthevariablesgetupdatedateachline:
Line Valueof‘a’
Valueof‘b’ Details
1 1 -
2 1 3 a=1,soa+2=1+2=3
3 1 6 b=2*b.Nowb=3,so2*b=2x3=6
4 5 6 b-a=6-1=5
5 5 6 print:56
Theinterpreteralwaysexecutesthecommandsinasequentialorder,updatinganyvariablesthatarechangedduringtheprocess.
Theloopstatementsbreakthissequentialflow,allowingustoaccessfunctionsdefinedanywhereinthewholecode.
LoopControlStatements
Whenshouldtheloopstart?Howlongshoulditcontinue,andwhenshoulditterminate?
Thisisachievedusingloopcontrolstatements.
Withoutthem,theinterpreterwilleithernotexecutethelooporifitdoeswillnevergetoutofit.Let’sseehowitworkspractically.
ListTypesandRangeFunctions
Tousethefor-loop,itisimportanttounderstandlisttype.Listsareorderedsequenceofdata.Someexamplesinclude:
[‘white’,‘red’,‘green’]
[1,2,3,4,5,6]
[‘word’,34,‘anotherword’,-4,‘last’]
[]#completelyemptylist
Thebasicfor-loopreliesonthelisttype.
THEFOR-LOOPThisloopiterates(repeats)afunctionorsetofcommandsforthefixednumberofparametersyougiveit.ThisisdifferentfromtheWhile-Loop,whichrunsaslongasaconditionistrue.
Forexample:
Ifitisrainingoutside,taketheraincoat.Whilethesunshines,themonkscontinueworkingtirelesslyonthefield
Hence,unlikethewhile-loop,thefor-looprunsonce.
Thesyntaxoftheforloopis
forvariable/functioninsequence/list:
indentedstatementstoloop
Here’sanexample:
forcountin[1,2,3]:
print(count)
print(‘Go’*count)
Theabovefor-loophasthefor-statement,thevariablewhichithastoworkon,andthelistofparametersithastoworkwith.
Theloophasthreeparametersandavariable.Whenitisexecuted,thetwolinesofcode
Line Valuein‘count’ Details
1 1 Takesfirstelementfromlist
2 1 print1
3 1 Applyoperator‘Go*1equal‘Go’;printsGo
1 2 Updatevaluetonextelement
2 2 print2
3 2 ‘Go*2equals‘GoGo’;printsGoGo;
1 3 changecounttothenextelementinthelist
2 3 print3
3 3 ‘Go’*3is‘GoGoGo’;printsGoGoGo;
Listcomplete,done.
Inthiscase,thefor-loopperformstwoactions:updatingthevariableinplaceof‘item’,andrunningtheindentedblockofcodeafter.Theaboveexampleusedthevariablewithintheloopaswell.
Asimplerloopcanalsobecreatedwithoutusingalist.ThisiswhereRange(apre-madefunctioninPython)canbeused.
forxinrange(7):
print(‘For-Loop’)
Noticethatthevariablexisnotusedinsidethebodyofthefor-loop.Youcanchoosethenumberoftimestheloopmustiterateorrepeatitself.
#aprogramforspecifiedrepetitions
n=int(input(‘Howmanytimesdoyouwanttorepeatthis?:‘))
forxinrange(n):
print(‘Repeating…’)
Onexecution,theprogramwillprintthestatement‘Repeating…’nnumberoftimesi.e.thenumberyouenterinthebeginning.
THEWHILELOOPItisaBooleanloopthatrepeatsthesamesetofcommanduntiltheoriginalconditionisFalse.
ThesyntaxforthewhileloopinPythonprogramminglanguageis:
whileexpression:
indentedstatement(s)
Aslongastheexpression(itsBooleancondition)holdstrue,theindentedblockofcodewillbeexecutedagainandagain.Themomenttheconditionbecomesfalse,theprogrammovesouttheloopandexecutesthenextlineoutsideofit.
Example
n=0
while(n<5):
print(‘Ihavecountedtill:‘,n)
n=n+1
print(“Goodbye!”)
Theabovewhile-loopholdstrueforaslongastheupdated‘n’hasavaluelessthan5.Themomentitreaches5theprogramwillmovetothefirstlineoutsideoftheloop(theun-indentedline).
Goodbye!
Howaboutaloopthatcanneverend?
Aninfiniteloopwherethefalseconditiondoesnotexist?Theseloopsareimportantforkeepingtheprogramrunningandseekingcontinuousinputfromtheuser.Ifaninfiniteloopwasnotrunning,anysmartdeviceorPCwouldshutdownafterloading(completingloading)itsoperatingsystem.
AloopbecomesinfiniteloopifaconditionneverbecomesFALSE.
n=1
whilen==1:#Thisistheofficialsecretforconstructinganinfiniteloop
a=input(“Enteravalue:”)
print(“Youentered:“,a)
print“Goodbye!”
CHAPTER8.LISTS,DICTIONARIES,TUPLES
Variablesallowustostoreinformationthatcanbechangedanytime.However,theystoreasinglepieceofinformationatatime:avalue,astring,etc.
Whatifweneedtostorealistofinformationthatwillnotchangeovertime?
Forexample,thecontactinformationofyourfamilymembers,thenamesofthemonthsoftheyear,oraphonebookwhereyouhavemultipleinformation(thenameofthecontactandrelatedphonenumbers.
ThisiswhereLists,Tuples,andDictionariescomein.Let’sbrieflydiscusseachsoyouknowthedifference,beforeusingtheminacode.
List
Asthenameimplies,itisalistofvalues.Thevaluesinalistarecountedfromzeroonwards(thefirstvalueisnumberedzero,thesecond1st,andsoon).Listletsvaluestoberemovedandaddedatwill.
Tuples
Theyaresimilartolistsexcepttheirvaluescannotbemodified.Oncecreated,thevaluesremainstaticfortherestoftheprogram.Again,thevaluesarenumberedforreference,startingwithzero.
Dictionaries
Likeanormaldictionary,itallowsyoutocreateanindexofwordswhereeachwordhasauniquedefinition.InPython,thewordiscalledthe‘key’whereasitsdefinitioniscalledits‘value’.Likeadictionary,noneofthewords/keysarenumbered.Thevaluesinthedictionarycanbecreated,removed,andmodified.
USINGTUPLESTuplesareeasytocreate.Nameyourtupleandlistthevaluesthatitwillcarry.Here’satupleforcarryingthemonthsoftheyear:
months=(‘Jan’,‘Feb,‘Mar’,‘Apr’,\‘May’,’Jun’,‘Jul’,‘Aug,‘Sept,‘Oct,\‘Nov,’‘Dec’)
Syntactically,atupleisacomma-separatedsequenceofvalues.Theparenthesisandthespaceafterthecommaaresimplyaconvention,andnotnecessaryforcreatingatuple.Furthermore,noticethe‘\’attheendofeachline?Itcarriesthelinetothenextline,makingbiglinesmorereadable.
Oncecreated,Pythoncreatesanumberedindextoorganizethevaluesinatuple.Startingfromzero,thevaluesareindexedintheorderyouenteredtheminthetuple.Theabovetuplebecomes:
Soifyouweretocallthetuple‘month’,youwillusetheindextocallit:
>>>month[2]
Mar
Additionally,Pythonhasaverypowerfultupleassignmentfeaturethatallowsustoassignvaluetovariablesontheleftwithvaluesontheright.Hence,forthe‘months’wehavecreatedearlier,wecanfurtherassignvaluestoeachofthevalueinthelist:
>>>(research,submitoutline,discussion,study,seminars,presentation,fieldtrip,submitpaper,paneldiscussion,finalpresentation,semesterends)=months
Theonlyrequirementisthatthenumberofvariablesontheleftmustequalthenumberofelementsdeclaredinthetuple.
Asimplewayoflookingatthisassignmentistotothinkofitastuplepacking/unpacking.Whenpacked,thevaluesontheleftarepackedtogether:
>>> months=(‘Jan’,‘Feb,‘Mar’,‘Apr’,\‘May’,’Jun’,‘Jul’,‘Aug,‘Sept,‘Oct,\‘Nov,’‘Dec’)
Intupleunpacking,thevaluesontheright(thenamesofthemonths)areunpackedintovariables/names/categoriesontheright:
>>> months=(‘Jan’,‘Feb,‘Mar’,‘Apr’,\‘May’,’Jun’,‘Jul’,‘Aug,‘Sept,‘Oct,\‘Nov,’‘Dec’)
>>>(research,submitoutline,discussion,study,seminars,presentation,fieldtrip,submitpaper,paneldiscussion,finalpresentation,semesterends)=months
>>>research
Jan
>>>seminars
May
>>>submitoutline
Feb
Anotherpowerfuluseoftupleiswhenyouhavetoswapthevaluesoftwovariables.Normally,youwouldhavetouseatemporaryvariableforswapping:
#Swap‘b’with‘a’
temp=b
b=a
a=temp
Atupleresolvesthisinasingleline:
(b,a)=(a,b)
Simple.Therighthandsideisatupleofvalueswhilethelefthandsideisatupleofvariables.Naturally,thenumberofvaluesmuchalwaysmatchesthenumberofvariables:
>>>(a,b,c,d)=(4,3,2)
ValueError:needmorethan3valuestounpack
USINGLISTSListsaresimilartotuples:theystorearangeofvaluesandaredefinedinasimilarfashion.However,unliketuples,youcanmodifythem.Thismakesthemthenormalchoicewhenitcomestostoringlists.Here’sanexampleofalist:
team=[‘Sam’,‘Michel’,‘Azazel’,‘Harrison’]
Noticethattheonlydifferenceinsyntaxistheuseofsquarebracketsinsteadofparentheses.Liketuples,thespacesafterthecommaareastandardpracticeforincreasingreadability.
Recallingthevaluesstoredinthelistarealsosimilartocallingvaluesinatuple:
printteam[3]
Harrison
Liketuples,youcanalsocallvaluesfromarangewithinthelist.Forexample,team[1:3]willrecall3rdand4thmembersoftheteam.
Theimportantthingwithlistsisitsabilitytoallowchange.Thisiscrucialwhenyouarebuildingdatabasesthatstorevalues(e.g.agrocerystore’sinventorywillhavechangingvaluesofthestockandneedtobeupdatedregularly).
Let’ssayyouinductanothermemberintoyourteam,howwillyouaddhim/her?
Valuescanbeaddedusingthe ‘append() ‘function.Thesyntaxoftheappendfunctionisoftheform:
list_name.append(value-to-add)
Hence,foranewmember,Gabriel:
team.append(‘Gabriel’)
Anddone!Thenewmember’snameisaddedafterthelastvaluestoredinthelist(‘Harrison’).
Howdoyouremoveanitemfromalist?SupposeMichelisnotgettingalongwithAzazelandGabriel,andisloweringthemoraloftheteam,etc.
Todeleteavaluefromthelist,youuse‘del’.RecallhowPythonindexesthelists,beginningfromzeroandonwards.SoMichelisthesecondvalueonthelist,makingitsindexnumbering‘1’.
#RemovingMichelfromthelist
team=[‘Sam’,‘Michel’,‘Azazel’,‘Harrison’,Gabriel]
delteam[1]
Youcandeletearangefromthelistbyassigninganemptylisttothem:
team[1:3]=[]
Nowtheteamthelastthreenamesremovedfromit.
WhatifyouwantedtoaddanewteammemberrightafterMichel?Normally,append[]addsthenewvalueattheendofthelist.
Yousimplytellafterwhichmemberthenewmembershouldbeplaced.Thisiscalledslicingthelist:
>>>team=[‘Sam’,‘Michel’,‘Azazel’,‘Harrison’]
>>>team[1:1]=[‘Gabriel’]
team=[‘Sam’,‘Michel’,‘Gabriel’,‘Azazel’,‘Harrison’]
METHODSTHATCANBEUSEDWITHLISTS.appendisjustoneoftheseveralmethodsthatareextensivelyusedwithcreatinglists.Othermethodsincludethefollowing:
.insertitisusedforpostinganewentryatthespecifiedindexnumber.Forexample,wanttoaddnumberstoyourlistofteam:>>team.insert(1,3320)
Thisinsertsthenumber3320atposition1,shiftingtheothervaluesupi.e.2ndbecomes3rdandsoon.
Ifyouwanttorepeatthelistwithinitself,thenyouwillsimplyuse .extend init.>>>team.extend([‘Sam’,‘Michel’,‘Azazel’,‘Harrison’])
>>>mylist
[‘Sam’,‘Michel’,‘Azazel’,‘Harrison’,‘Sam’,‘Michel’,‘Azazel’,‘Harrison’]
Ifyouwanttofindtheindexnumberofanyvalueinthelistuse .index
>>>team.index(3)
‘Harrison’
Reversethewholelistusing .reverse
>>>team.reverse()
[‘Harrison’,‘Azazel’,‘Michel’,‘Sam’]
Removethearepetitiveitemorthefirstuseofanyitemusing .remove
>>>team.remove(‘Sam’)
[‘Michel’,‘Azazel’,‘Harrison’]
Orincaseyouhaveanumberlist,andyouwanttosorttheminascendingorder,use .sort
>>>numlist.sort()
[1,3,3,3,7,9,10,10,24]
USINGDICTIONARIES
Previouslywehavecreatedlistsofnamesofateamandatuplewithvariableandvalueassignment.However,inbothofthem,thevalueoftheindexedvariablecanonlybecalledbygivingtheindexnumberforthatvalue.
Whatifyouwanttocreateadatabase,orasmallphonebook,thatgivesyouthedetailsofavariablewhenyouenteritsnameinsteadoftheindexnumber?Listsandtuplescannotgiveyoutherequiredaccessibility.
Dictionariescan.
Recallthatdictionarieshavekeysandvalues.Inaphonebook,youhavenamesofthepeopleandtheircontactdetails.Seeanysimilarities?
Creatingadictionaryissimilartomakingalistoratuple,exceptaslightdifferenceinitsbrackets.
(Tuples)useparenthesis[Lists]usesquarebrackets{Dictionaries}usecurlybraces.
Here’sanexampleofadatabaseformoneyowedtoeachmemberyourbusinessteam:
#Initialbusinessfunds:
Logbook={‘SamKim’:4000,‘MichelSanderson’:4300,\
StarkGarret’:5120,‘AzazelForest’:3230,‘HarrisonSnow’:6300}
Noticethesyntax:
Key:Value
Hereishowthekeysareusedtolookupthecorrespondingvalue,justlikeinadictionary:
>>>print(logbook[“AzazelForest”])
3230
DICTIONARYOPERATIONSYoucanaddnew key:value pairsinthedictionaryaswellasremoveandupdateexistingdictionaryentries.
ADDINGNEWENTRIESTODICTIONARIESToaddnewentriesinyourexistingdictionary,yousimplydefinethemasfollows:
#AddingGabrieltothelogbook:
logbook[‘GabrielSky’]=7300
Theabovestatesthatthekey:value=‘GabrielSky’:7300
DELETINGENTRIESNowwhatifyouwanttodeletesomeentries?Thisisdoneexactlyhowitwasdoneforlists.Nowlet’ssayMichelhasbeenpaidinfull,andhehasresigned.Youwanttodeletehisaccountpermanently.Justlikewiththelists,youuse‘del’:
delphonebook[‘MichelSanderson’]
The‘del’operatorwilldeleteanyvariable,entry,orfunctioninalistoradictionary.Anotherexampleisofasmallinventoryinagrocerystore.Thedictionarycontainsthenamesofvariousfruitsandtheiravailability(numberinstock):
>>>inventory={“apples”:350,“bananas”:230,“Mangos”:100,“Peaches”:250}
>>>print(inventory)
NowwhatifMangosgooutofstock?Wehavetwooptions:ofdeletingthekey:valueorsimplychangethevalueofthekey:
#deletingthevalue
>>>delinventory[“mangos”]
>>>print(inventory)
{“apples”:350,“bananas”:230,“Peaches”:250}
Incasethestoreisreceivingmorestock,theweneedtheoptiontosimplyupdatethevaluewithanewvalue:
>>>inventory[“Mangos”]=0
>>>print(inventory)
{“Mangos”:0,“apples”:350,“bananas”:230,“Peaches”:250}
Let’ssaywehaveanewshipmentforMangowithinthehour,anditwilladd150additionalMangostotheinventory.Thiscanbehandledlikethis:
>>>inventory[“Mangos”]+=150
>>>print(inventory)
{“Mangos”:150,“apples”:350,“bananas”:230,“Peaches”:250}
Tuples,lists,anddictionariesplayanimportantroleinwritingsimplerandmorepowerfulcodesinPython.Theybecomeevenmoreimportantwhenwestartprogrammingusingandinterfacingobjects.
CHAPTER9.OBJECTORIENTEDPROGRAMMING
Historically,acodehasmostlybeenviewedasalogicalprocedurewheredataistakenasinput,processed,andusedtoproduceoutputdata.Consequently,thechallengeofprogrammingwasseenhowtocreatelogicforusingthedataandnotdefiningthedata.
Object-OrientedProgramming(OOP)isaprogramminglanguagemodelthatreliesonbuildingcodeusingobjectsanddataratherthan“actions”and“logic”.Ittakestheviewthatwhatweshouldreallycareabout(andwhichprogrammersalwayshave)areobjectsthatwecanmanipulateinsteadofthesequentiallogicneededtomanipulatethem.
Object-orientedprogramminghasitsrootsinthe1960s,howeveritbecamethedominantparadigmofprogrammingasthecomplexityandsizeofthesoftwarebegantoincreaserapidly,givingwaytomorepowerfulandcomplexsystems.
Examplesrangefromelectronicdevices(whopropertiesandattributescanbenamed),tohumanbeings(describedintermsoftheirattitudesandproperties),allthewaytotheappsweuseonoursmartphones.
GETTINGSTARTEDWITHOOPThefirststepinapplyingOOP(whichyoumustbecausePythonisanobjectorientedprogramminglanguage)istoidentifytheobjectsthatareneededtobuildthecode,andhowtheyrelatetoeachother,andwhichyouwanttomanipulate.
Thoughitiscalleddatamodeling,thinkofitlikebuildingastrategyorablueprintforcreatingsomething.
InPython,onceyouhaveidentifiedandobject,ageneralizedclassofobjectsinitsnameiscreated.Thisclassdefinesthekind/typeofdatathisobjectcontainsandanylogicsequenceswhichitcanmanipulate.
Thelogicsequenceusedforeachclassisknownasitsmethod,whereastheinterfacesthroughwhichtheobjectscommunicatewithoneanotherarecalledmessages.
BENEFITSOFUSINGOOPThisframeworkoffersnewerwaysofprogramminginPython.Importantbenefitsinclude:
Dataclassesallowsaprogrammergreaterflexibilityandcreativityincreatingnewtypesofdataforusewiththeprogram.EvenifcertaindatatypesarenotavailableinPython,youcaneasilycreatethemasaseparateobjectandusethemlikefunctions(crudelyspeaking)insideyourcode.
Thedataclassmakesitpossibletoeasilydefinesubclassesofdataobjectsthatcaneithershareallthepropertiesofthemainclasscharacteristicsorsomeofit.Thispropertyiscalledinheritancewherethesubclassinheritspropertiesandattributes.ThisabilityoftheOOPframeworkallowsmorerobustanalysisofdata,allowsmoreaccuratecoding,andsignificantlyreducesdevelopment.
OOPallowsdatahidingwhichpreventsaccidentalsharingofdataacrossthecode.Sinceeachclasshasapredefinedsetofattributesanddatapropertiesthatitmustbeconcernedwith,anyinstancesofthisobjectwhereusedthroughoutthecodewillonlyuseitsspecifieddata,henceavoidinganyinstancesofdatacorruption.
Classesoncedefinedareeasilyre-useable.Theobjectoncecreatedbecomesglobal,inthesendthatitcanbeusedbyboth,theprogramforwhichitwascreatedandbyotherOOPcodesusingthesamemachine/network.
CHAPTER10.CLASSES,OBJECTS,INHERITANCE
Programmersaresupposedtobelazy.Theyhavetofindthemostefficientwayofdoingthings,savingtimeformorecodingortodowhattheywill.
Thepurposeofprogrammingistosimplyandautomateactionsandhenceavoidrepeatingwritingthesamecodeagain.Recallusingfunctions.Onceyouhavecreatedafunction,youcancallitandre-useitanywhereinthecodeandtheinterpreterwillknowwhatyouareaskingfor.
However,functionshavelimitations.Theyusedatabutcannotstoreandholdinformation.Everytimetheyarecalled,theystartafresh.Nowattimescertainfunctionsandvariablesarerelatedtooneanotherveryclosely,andwheneverthefunctionisrun,thosevaluesneedtobefetchedandcomputedalongsidenewdata.
Butwhatifweneedafunctiontogeneratemultipleoutputsandvaluesinsteadofjustoneoutput?Whatyouneedhereistheabilitytogroupmultiplefunctionsandassociatedvariablesinoneplacesothattheycaneasilyinteractwithoneanother.
Taketheexampleofyourteam.
Allofthemhavejoinedagolfcourseandboughtnewgolfclubs.
Yourprogramwillstoredifferentvariablesregardingtheclubs(theirshaftlength,weight,forgiveness,spin,etc.),andyouwanttokeeptrackoftheimpacteachpropertyexperiencesovertime(weakenedshaft,increasedfrustration,scratches,etc.).Supposeyoumakefunctionsforeachteammember,whatiftheydecidetohavemorethanoneclub?
Willyouwriteawholechunkofcodeforeachdifferentgolfclub?
Giventhatmostoftheclubssharecommonfeatures,theidealthingtodowouldbetocreateabasiccategory,oranidealcategorythatdefinesalltheattributesofthegolfclub.Hence,wheneveryoucreateanewclub,allyouhavetodoisspecifytheneworchangedattributesandanewitemwillbecreatedinthedatabase.
Thisiswhereclassesandobjectscomeintoplay.Theyallowyoutocreatesmallindependent‘communities’wherefunctionsandvariablescaninteracttogether,caneasilybemodifiedasneeded,andremainunchanged(andunaffectedbyothercode).
Westartbuildingsuchobjectsbyfirstcreatingclasses.
CREATINGACLASS
Aclassisablueprint,anideaofsomething.Itdoesnotexistasausablefunction,ratheritdescribeshowtomakesomething.Thisblueprintcanbeusedtocreatealotofobjects.
Youcancreateaclassusingaclassoperator.Thegeneralsyntaxforaclassis:
classname_of_my_class:
[statement1]
[statement2]
[etc]
Here’sanexample
classnew_shape:
def__init__(self,x,y):
self.x=x
self.y=y
shape_details=“Thisisanundescribedshape”
creator=“Noonelaysclaimtocreatingthisshape“
defcreatorName(self,text):
self.creator=text
defdetail(self,text):
self.shape_details=text
defperimeter(self):
return2*self.x+2*self.y
defarea(self):
returnself.x*self.y
defscaleSize(self,scale):
self.x=self.x*scale
self.y=self.y*scale
Theaboveisavaguedescriptionofashape(squareorrectangle).
Thedescriptionisdefinedusingthevariablesyouhaveusedfortheshape,andusingthefunctionsyouhavedefinedtheoperationsthenewclass‘new_shape”canbeusefor.Butyouhavenotcreatedanyactualshape.Itissimplyadescriptionthatneedsvaluestodefinehowitwouldlook(theheight‘x’andwidth‘y’),andwhichwilldefineitsproperties(areaandperimeter).
Wonderingwhat‘self’isallabout?Recallthatyouhavenotcreatedanactualshapeyet.‘self’ishowthingsarereferredtointheclassfromwithinitself.Itisaparameterthatdoesnotpassanyvaluetothefunction.Asaresult,theinterpreterdoesnotrunthecodewhena
classisdefined.Itconsideredasapracticeinmakingnewfunctionsandpassingvariables.
Allthefunctions/variablesthatarecreatedonthefirstindentationlevel(thelineofcodeindentedrightafter)areautomaticallyputintoself.Ifaparameterorafunctioninsidetheclasshastobeusedwithinthatclass,thenthenameofthefunctionmustbeproceededwithaself-dot(self.)e.g.self.xasusedinthepreviouscode.
USINGACLASSWecancreateaclass.So,nowthequestionis:howdoyouusethemagicalblueprinttocreateanactualshape?
Weusethefunction_init_tocreateaninstanceofnew_shape.
Assumingthatthepreviouscodehasbeenrun,letscreateashape:
rectangle=new_shape(80,40)
Thisiswhere__init__functioncomesintoplay.Wehavealreadycreatedaclass(ablueprintnormallycalledaninstancefortheclass).Wedidthisbygivingit:
Aname(new_shape)Valuesinbrackets,whicharepassedpasstothe__init__function.
Usingtheparametersgiventotheinitfunctions,theinitfunctiongeneratesaninstanceofthatclass,assigningitthenamerectangle
Now,thisnewinstanceofournew_shapeclasshasbecomeaself-containedcollectionoffunctionsandvariables(wewilldiscussinheritancelater).Earlierwewereusingself.toaccessthevariablesandfunctionsdefinedinthatclassbecausewewereaccessingitfromwithinitself.Now,wewillusethenamewehaveassignedtoitstangibleform(rectangle).Wewillaccessthevariablesandfunctionsintheclassfromoutside.
Oncetheabovecodehasrun,wecanaccesstheattributesofourclasstocreateashapewiththefollowingcode:
#Calculatingtheperimeteroftherectangle:
printrectangle.perimeter()
#Calculatingtheareaoftherectangle:
printrectangle.area()
#detailsabouttherectangle
rectangle.describe(“Arectanglethatistwiceaslongasitiswide.“)
#Scalingtherectangletohalfitssize,i.e.makingit50%smaller
rectangle.scaleSize(0.5)
Noticehowtheassignednameofthenewobjectisbeingusedwhentheclassisbeingusedoutsideofitself.Whereas,whenitwasbeingusedfromwithinitselfthe self.operatorwasbeingused.
Whenusedfromoutsideofitself,wecaneasilychangethevalueofthevariablesinsidetheclassandaccessitsfunctions.Thinkoftheclasslikeafactorythatassemblesnewproductswhengiventherightinput.Whenusingclasses,wearenotlimitedtoasingleinstance.Wecanhavemultipleofthem.Forinstance,couldcreateanotherobjectnamedthin,long,andsturdyrectangles:
thinrectangle=new_shape(100,5)
longrectangel=new_shape(100,20)
sturdyrectangle=new_shape(100,90)
Evenwhenwehavecreatedthreeinstances,allofwhichreliedonthevariablesandfunctionsfromthesameclass,ALLOFTHEMarecompletelyindependentofoneanotherandcanbeusedcountlesstimesthroughouttheprogram.
APPRECIATINGTHEGEEKTALKTheObject-oriented-programmingisaframeworkwithitsspecificsetofwordsusedtodescribeaprogrammingaction.Youshouldknowthebasiclingotoavoidanyconfusionincompanyofanotherprogrammer.Herearesomebasicwords:
Describingaclassmeansdefiningit(similartofunctions,albeitmoredetailed)EncapsulationisthegroupingofsimilarfunctionsandvariablesunderasingleclassClassitselfcanbeusedintwoinstances,todescribethechunkofcodethatdefinesaclassandtheinstancewheretheclassisusedtocreateanewobject.Aclassisalsoknownasa‘datastructure’.ItcanholddataandhasthemethodstoprocessdataprovidedtoitTheattributeofaclassarethevariablesinsidethemAmethodisthefunctionyouhavedefinedinsidetheclassAclassitselfisanobject,andinthesamecategoryofthingssuchasdictionaries,variables,lists,etc.
INHERITANCEWe’vetalkedaboutinheritanceinfunctionsandearlierinthesamechapter.Whatisitandwhyisitimportant?Let’sfirstrecapwhatwehavedonesofarintermsoffunctions,variables,andcreatingclasses.
Earlieryousawhowwecangroupadiverserangeofvariableandfunctionstogether.Thisallowsthedataandtheprocessingcodetobepresentinthesamespot,makingiteasiertoreadthecodeaswelltoexecuteitacrossthecodefromasinglespot.Now,theattributeswegrantedtotheclass(variables)andthemethodsitcanusetoprocessthedata(thefunctions),allowsustocreateinnumerableinstancesofthatclasswithoutwritingnewcodeforeverynewobjectthatwecreate.
Whatifwewanttocaterananomalyinourdatabase?Imagineifwehaveashapewithadditionalfeatures,onesthatdoessharecommonfeatureswiththeoriginalclassbuthasadditionalfeaturesthattheoriginalclasscannotprocess?
Creatinganewcodetocaterdifferencesisnottherightwaytohandleit.Thisiswherewemakeachildclassthatinheritsallthepropertiesoftheidealclasswhileaddingitsownnewfeaturestoit.
Thisiswhereinheritancecomesintoplay,andwhichPythonmakesexceptionallyeasytoimplement.
Howdoesitwork?
Wedefineanewclass,usingtheexistingclassasits‘parent’class.Consequently,thechildclasstakeseverythingfromtheparentclasswhileallowingustoaddnewfeaturesandattributesandmethodstoit.
Let’sbuildonthenew_shapeclass:
Here’sanexample
classnew_shape:
def__init__(self,x,y):
self.x=x
self.y=y
shape_details=“Thisisanundescribedshape”
creator=“Noonelaysclaimtocreatingthisshape“
defcreatorName(self,text):
self.creator=text
defdetail(self,text):
self.shape_details=text
defperimeter(self):
return2*self.x+2*self.y
defarea(self):
returnself.x*self.y
defscaleSize(self,scale):
self.x=self.x*scale
self.y=self.y*scale
Nowsquareisalsoconsideredaformoftherectangle,howeveritswidthandlengthareequaltooneanother.Nowifwewanttodefineanewclassusingtheexistingnew_shapeclass,thecodewouldlooklikethis:
classsquare(new_shape):
def__init__(self,x):
self.x=x
self.y=x
Thisisquitesimilartohowwedefinedthenew_shapeclass,exceptthatwehaveusedtheparentclassasthesetofparametersthatneedtobeinherited.Noticehoweasyitwastocaterthisnewobjectwithouthavingtoredefineandwriteitscodeseparately.
Wechangedonlywhatneededtobechanged,borrowingtherest.Wehavemerelyredefined__init__functionofnew_shapesothattheheightandwidth(xandy)becomethesame.However,thenewvariablesdefinedinthechildclasswillneveroverwritetheonespresentinnew_shape.
Now,squareitselfhasbecomeanewclassandwecanuseittocreateanotherclassaswell!Youseeapatternhere?Itslikealegopuzzle,youcreateobjectsandyouusethemasbrickstobuildbetterandmorecomplexobjectsandprograms.
Let’screateadoublesquare,sothattwosquaresarecreatedsidebyside:
class2square(Square):
def__init__(self,y):
self.y=y
self.x=2*y
defperimeter(self):
return2*self.x+3*self.y
Noticethatthistimewehaveanadditionalmethod(afunction)inthecodeaswell.Wehaveredefinedtheperimeterfunctionbecausetheonethatsquarehasinheritedformnew-shapecannotcatertotheneedsofthisnewclass.
Ifyoucreateaninstanceof2square,yourdoublesquareswillallhavethesameattributesandpropertiesdefinedbythe2squareclassandnotthesquareornew_shape.
POINTERSANDDICTIONARIESOFCLASSESPreviously,wehadseenhowvariableswappingworks,e.g.var1=var2wouldswapthelefthandsidevariablewiththevaluestoredintherighthandsidevariable.
Thesamedoesnotholdtruewhenitcomestocreatingclassinstances.Whenyouwriteinstance1=instance2,whatisactuallyhappeningisthatthefirstclassispointingtotheclassontheright.“Pointing”meansthatboththenamesofinstancesrefertothesameclassinstance,andthatthesameclassinstancecanbeusedbyeithername.
Thisbringsustodictionariesofclasses.
Buildingonhowpointerswork,Pythonletsuseasilyassigninstanceofclasstoanentryinalistordictionaryaswell.Butwhydoit?What’sthebenefit?
Itallowsustocreatevirtuallyunlimitednumberofclassinstancestorunfromourprogram.Here’sanexampleofusingpointerstocreatedictionaryinstances.Assumingtheoriginaldefinitionofnew_shape,andthatthesquareand2sqaureclasseshavebeenrun:
#Createadictionary:
dictionary={}
#Next,createsomeinstancesofclassesinthedictionary:
dictionary[“2square1”]=2square(5)
dictionary[“longrectangle”]=new_shape(100,30)
Nowyoucanusethemlikenormalclasses!
dictionary[“2square1”].creatorName(“PythonCoder”)
printdictionary[“2square1”].author
printdictionary[“longrectangle”].area()
Now,youhavereplacedthepreviousnamewehadcreatedforourcreationwithanarguablybetternamebycreatinganewdictionaryentry.
CHAPTER11.DEBUGGING
CodesremindusoftheimportanceofpayingattentioninEnglishgrammarlessons,andhowouroverrelianceonauto-correctfeaturesinwordprocessingsoftwarehasmadeussusceptibletooverlookingsmallmistakes—acommahere,acolonthere,andamisspelledvariablethere,amongothers.
Mistakes,weathersmallorlargecanpullthebrakesonaprogram.Asaresult,yourcodewillnotrunatall,displayerrors,orgiveobnoxiousresults.Thisiswhereyouhavetotroubleshoottheprogram,locatetheproblem,andcorrectit.
Inprogramminglingo,that’scalleddebuggingyourprogram.
Smallmistakessuchaswrongsyntaxordeclaringnon-existingvariables,ormorefundamentalmistakessuchasinsufficientunderstandingoftheproblem(andhencetheobjectsthatneedtobecreatedandtheirinteraction),andincorrectflowofdatacanmakethecodedysfunctional.
Giventhatonlyyoucanbestunderstandyourcode,youwilloftenfindyourselfinapositionwhereyoualonearerightpersontosaveyourcode.However,decadesoftestinghavegivenusafewtipsandtricksfordebuggingyourcode.
However,beforewemoveintothetips,itisimportantthatyoudownloadyourfirstdebugger.
DOWNLOADADEBUGGER
Why?
Pythonalreadyshipsinwithitsbuilt-indebugger.
Yes,Pythoncomesequippedwithadebugger,sportingabasiccommandlineinterfaceandwithvariousfeaturesandoptions.However,itlackscertainfeaturesthatwillsimplifydebuggingforbeginners,includingstacktracesanddifferentiatingcoloringfordifferenttypesofcode.
So,here’sabetteroptionforadebuggingtool.
DownloadPudb2015.3,afullscreenconsolebasedprogramdebugger.IthasamodernGUI-basedenvironment,andallowsyoutodebugyourcoderightwhereyouwriteit:ontheterminal.
CHAPTER12.NEXTUP
ThiseBookismeanttointroduceyoutothebasicsofPythonlanguage:itsfundamentalbuildingblocks,theirsyntax,theirbasicuses,andhowtheyarerelatedtooneanotherincreatinglargerprograms.However,likeanyotherlanguage,theonlywaytoimproveandexcelatitistoconsciouslytrytouseittosolveproblems.
Havingintroducedthebasicbuildingblocksofthelanguage,it’snowlikechess:youknowthecomponents,youknowthebasicrules,andyouknowthemoves(bothlegalandillegal).Readingmoreaboutitwillnothelpyouontheboard.Onlypracticewill.
Sowhatshouldyoudonext?
Pythonisalanguageforcommunicatingwithcomputingdevices,andmostofwhatyouwillbewritingwillneverbevisibleonthefrontend.Imean,howmanyappshaveyouused,orgameshaveyouplayedwhereyouknowthecodelineyou’reonrightnow?
Understandthatyouhaveonlyscratchedthesurface.Asyoustartbuildingcodewiththebasics,youwillcomeacrossadvancedcodesthatyoucanbuildon.ContinuepracticingandsharingyourquestionswithablossomingonlinecommunityofPythoncodesandfans.
PythonisoneofthemostadvancedandoneofthesimplestOOPlanguagesontheplanet.Bepatient,andmasterthebasicsbeforemovingtowardsthemoreadvancedfeaturesofthelanguage.
ABOUTTHEAUTHOR
Inspiredbylegendaryfemalecoder,AugustaAda,VivianhasbeeninthesoftwareengineeringsinceshewasincollegeattheUniversityofSydney,Australia.WhilestudyingatUofS,Viviantookthepathmostfemaleswouldnotstudy.SheenrolledintendingtomajorinArchitecture,butafter2semestersshebegantodesignwebsitesforlocalcharities.HerloveofthewebtookoffandswitchedmajortoComputerScienceandInformation.
Sincegraduatingin2012,Vivianashasgoneontodoawidevarietyoffreelanceprojectsandsub-contractworkinmobileandwebdevelopment.Sheoftenvolunteersinworkshopsandtrainingprogramstohelpthoseinterestedinlearningallaboutsoftwaredevelopment.
Viviantravelstheworldandworksfromherlaptopmostofthetime.Sheisinterestedinhelpingotherslearnhowtoprogramandstartnewcareersinthewebindustry.