PYTHONMADESIMPLE
©Copyright2015-Allrightsreserved.
Thisdocumentisgearedtowardsprovidingexactandreliableinformationinregardstothetopicandissuecovered.Thepublicationissoldwiththeideathatthepublisherisnotrequiredtorenderaccounting,officiallypermitted,orotherwise,qualifiedservices.Ifadviceisnecessary,legalorprofessional,apracticedindividualintheprofessionshouldbeordered.
FromaDeclarationofPrincipleswhichwasacceptedandapprovedequallybyaCommitteeoftheAmericanBarAssociationandaCommitteeofPublishersandAssociations.
Innowayisitlegaltoreproduce,duplicate,ortransmitanypartofthisdocumentineitherelectronicmeansorinprintedformat.Recordingofthispublicationisstrictlyprohibitedandanystorageofthisdocumentisnotallowedunlesswithwrittenpermissionfromthepublisher.Allrightsreserved.
Theinformationprovidedhereinisstatedtobetruthfulandconsistent,inthatanyliability,intermsofinattentionorotherwise,byanyusageorabuseofanypolicies,processes,ordirectionscontainedwithinisthesolitaryandutterresponsibilityoftherecipientreader.Undernocircumstanceswillanylegalresponsibilityorblamebeheldagainstthepublisherforanyreparation,damages,ormonetarylossduetotheinformationherein,eitherdirectlyorindirectly.
Respectiveauthorsownallcopyrightsnotheldbythepublisher.
Theinformationhereinisofferedforinformationalpurposessolely,andisuniversalasso.Thepresentationoftheinformationiswithoutcontractoranytypeofguaranteeassurance.
Thetrademarksthatareusedarewithoutanyconsent,andthepublicationofthetrademarkiswithoutpermissionorbackingbythetrademarkowner.Alltrademarksandbrandswithinthisbookareforclarifyingpurposesonlyandaretheownedbytheownersthemselves,notaffiliatedwiththisdocument.
BonusFreePythonProgrammingVideos
Whenyousubscribeviaemail,youwillgetfreeaccesstoatoolboxofexclusivesubscriber-onlyresources.Allyouhavetodoisenteryouremailaddresstotherighttogetinstantaccess.
Togetinstantaccesstotheseincredibletoolsandresources,clickthelinkbelow:=>Clickhereforthebonuscontent<=
TableofContents
IntroductionChapter1:SettingUpPythononYourcomputerChapter2:InteractingwithPythonChapter3:Boolean’sinPythonChapter4:Boolean’sandConditionalexpressionsChapter5:Useofif–elifstatementsinmakingMultipleTestsinPythonChapter6:UseofNestedControlflowstatementsinPythonChapter7:CompoundBooleanExpressionsinPythonChapter8:PythonDataVariables(Numbers,Lists,Tuples,StringsandDictionaries)Chapter9:BasicOperatorsinPythonforCalculationsChapter10:OpeningandClosingFilesChapter11:ReadingandWritingFilesinPythonChapter12:ManagingDatabasesConclusionBonusFreePythonProgrammingVideos
Introduction
Iwanttothankyouandcongratulateyoufordownloadingthebook, “PYTHONMADESIMPLE” .
ThisbookcontainshassimplelessonsononecanusenumbersandtextsinpythonasawayofinteractingwithPython.
EverychapterinthisbookhaswellorganizedandnumberedstepswhichyouwillneedtofollowsoastogrowyouexpertiseintheuseofPythonasscriptinglanguage.Inaddition,thisbookalsoprovidesyouwithcodeswhichyouwillneedtopracticewithinyourPythontolearnhowtorunPythoncodes.
ItismyhopethattypingthecodeswillincreaseyourknowledgeandunderstandingofthevariouscapabilitiesthatcanbeachievedinPython.
Itismydelightthatafterreadingthisbook,youshouldexpecttohaveamuchbetterunderstandingofhowyoucancodeandwritealgorithmsthatwillsimplyworkforyouinusingNumbersandTexts.ThiswillmakeyourlifeeasierandincreasepotentialasaPythonExpert.
Ibelievethattheinstantyoumadeadecisiontoreadthisbook;youwereheadedintherightdirection.Itisindeedafantasticideatoreadthisbook.Itismyanticipationthatafterreadingthisbook,youwillhavesignificantlygainedmuchknowledgeandskillsinusingPythonnotonlyforusingnumbersandtexts;ButalsoyourgeneralproblemsolvingskillsinPython!
Isn’tlearningPythonthiswayafantasticidea?Well,I’mhappythatyouchosethisbookasyourguidetolearningPythonandgettothenextlevelinPythonprogramming.I’mindeedveryexcitedforthegreatpotential.
Ithankyouinadvancefordownloadingthisbook,Ihopethatyouwillbenefitfromthisrichresourceandhopethatyoupracticethisonadailybasis.
Chapter1:SettingUpPythononYourcomputer
Tobeabletousepython,youneedtoensurethatyourcomputerhasalltherequirementsneedstorunpython.Thischapteroffersyoualltheinstructionsyouneedtofollowtogetstarted.Therearedifferentsettingsforpythondependingwiththecomputeryouwanttouse.
IfyouareusingMacOSXcomputers:YouwillnotneedtoinstallPythonprogramsinceyoualreadyhaveaPython2.NeitherwillyouneedaanyotherversionsuchasPython3.
Warning
YoumanyneedotherprogramssuchasPowerShellifyouaregoingtousewindows,TerminalwhenusingOSXandbashifyoupreferusingLinux.Butifthisisyourfirsttimeusingthisprogram,thenyouwillneedtolearnhowtheycanbeusedfirst.
However,themostbasicrequirementsincludehavingPythonprogramandeverythingstartshere:HowdoIinstallpython?
Thisisaverysimpleprocess
First,downloadthelatestversionofpythonandforcompatibilitywithotherprogramsthatyoumayneed,usetheproductversion2.7.1ofpython.Finditinthefollowinglink:PythonDownload.Doyouknowhowtoinstallaprogramonacomputer?Yes,justdoubleclicktheicondownloadedfromyourdownloadfolderandwaitforfurtherinstructions.But,ensurethatyouacceptallthedefaultsettingsoftheprogramtillyouareaskedtopressthefinishbutton.Theprogramwilltheninformyouiftheinstallationiscompleted.
GettingreadytousePython
Checktoseethatallprogramsareintherightlocations:startfromMyComputer,locatethedirectoryC:\python27.Youshouldbeabletolocateallthepythonprogramfileshere.
Next,copyallthedetailsofthedirectorybeginningfromC:to27andexitfromthewindow.Then,goforthestartbutton,andrightclickonMyComputer.Selectproperties.Select;AdvancedSystemSettings.ClickonEnvironmentVariables.Inthatfolder,searchforthefoldervariablepath.GoforthefilecalledPathandrightclickonit,selectedit.SearchforthefieldcalledVariableValueusingtherightarrow.Introduceasemicolonattheendofthewordandpastthedirectorypathofthepythonfolderyouhadcopiedpreviously.Thenpressontheokaybutton.
HowtocreateafirstPythonProgram
Gotostart,andthenmycomputerSelectdriveCandclickonit.ClickonthePython27folder.Next,rightclickonthespaceandcreateanewfolder.NamethenewfolderPythonProgramsSaveallthenewprogramsyoucreateinthisfolder.ThengotoStartandtypeRunintheSearchboxatthebottomandpressENTER.Next,typenotepadinthenewwindowfieldreferredtoasOpen.TypethefollowingwordsinNotepadjustasitiswrittenhere:
#File:Hello.pyprint"HelloWorld!"
GoforthefileinthecontrolpanelandselectSaveAs.InthesectionSaveinbrowsefortheC:driveandthenselectthefolderPythonPrograms.ForthefieldFilenameremoveeverythingthatisthereandtypeinHello.py.InthefieldSaveastypeselectAllFiles
ClickonSave.YouhavejustcreatedyourfirstPythonprogram.
Runtheprogramyouhavejustcreated
ClickontheStartbuttonandclickonRun.InputcmdintypingfieldfollowedbyOK.Anewdarksmallwindowwillpopup.Inthenewwindow,typecdC:\andthenpressthekeyEnter.However,incaseyoutypedir.YouwillgetalistofallthedirectoryfoldersinthedriveC:\.SearchforthefolderlabeledPythonProgramscreatedbyyouinthepreviousstep.Next,typecdPythonProgramsandpresstheEnterbutton.Thisisadirectwayofaccessingthepythonprogramsfolder.JustbytypingdirandyouaresupposedtoseethefilenamedHello.py.TryrunningtheprogrambytypingpythonHello.pyfollowedbyEnter.TheoutputshouldbeasinglelinereadingHelloWorld!Thisisyourfirstprogram,Bravo!!YouhavejustbeenabletocreateandrunyourfirstPythonprogram.
PythonforMacUsersWhenusingMac,PythoncomesalreadyinstalledwithyourMacOSX.Theversionshowevermayvary.Youcandownloadanewversionofpythonwhentheversionyouhaveisaveryold.ThiscanbeaccessedbyfollowingthehyperlinkhereDownload.ThisisoneofthelatestbinaryversionsofPython.ItisabletorunsonbothPowerPCandIntelsystems.Afterthedownloadiscomplete,installitonyourcomputer.
Youarenowreadytocreateyourfirstprogram!
HowtostartIDLEonMac
1. Whileinwindowswetalkofthestartbutton2. InMac,itisinitiatedfromtheTerminalwindow,andthentyping
python.Thiswillstartthepythonshellautomatically.3. Usethe>>>topromptforPythonshell.
4. Then,youcantypeinthepythonshellpromptimportidlelib.idle5. ThiswillactivatetheIDLEIDE
PythonIDLEonWindowsandMac
GotomyprogramsLocatepythononthelistofprogramsSelectIDLEtostartIDLEThengotoFile,andselectNewWindowTypeyourprogramin“HelloWorld”Next,locatetheFilemenuandclickonSave.TypeinHelloworld.pyThisallowsittobesavedasaplaintextfile.Theextensionofthefilename(.py)helpstoenablethepythontextreadertobeabletoopenitandreadit.ItalsoenablesotherprogramswhicharetexteditorssuchasNotepad,Notepad+++orTextEdittoreadtheprogram.Aftersavingtheprogram,gotoRunandselectRunModuleorusetheF5keyonyourcomputertorunyourprogram.Theoutputshouldread:Helloworld!
IfusingMacOSX
Thefollowingwillneedtobedone:
1. Usingyourbrowser,downloadtheTextWranglertobeusedasatexteditorandinstallitonyourcomputer.Thiscanbeaccededonhttp://www.barebones.com/products/textwrangler/
2. Theeditor(TextWrangler)tobeplacedinthedockswhereitcanbeaccessedveryeasily.
3. Gototheterminalprogram;searchfortheTextWranglerandyoushouldbeabletofinditwithease.
4. Next,placeyouterminalinyourdockstoo.5. Then,trytorunyourTerminalprogram.6. Intheterminalprogram,runpython.Thisisperformedbytypingthe
thingsyouneeddoneandhittingreturn.So,typePythonandhitRETURN.
7. Next,trytoexitPythonbyTypingquit(),Enter.Thiswillexityou
fromPython.8. ThiswillReturnyoutoasimilarpromptthatwasthereinthe
programevenbeforeyouenteredPython.Ifnotthere,seektofindoutwhythisisnotthere.
9. YoumayalsoneedtolearnhowonecanmakeadirectoryintheTerminal.10.Moreover,findouthowthedirectorycanbechangedfromtheTerminal.11.Afilecanalsobecreatedusingyoureditorinthedirectory.Followthefile,then,SaveoruseSaveAsandthenlocatethedirectoryyouhavecreatedforsavingyourPrograms.12.Tryalso,gettingbacktotheterminalusingyourkeyboardbyswitchingwindows.13.GetbacktotheTerminalandtrytolocateyournewlycreatedfile.
Inwindows:
1. Youmanyalsoneedtohavenotepad++.Thiscanbeaccessedfromhttp://notepad-plus-plus.org/onyourbrowser.ThisisanalternativetextEditor.Installitonyourcomputer.Thisdoesnotrequireyoutobetheadministrator.
2. PlaceitonthedesktoporstartbuttonwhereitcanbeeasilyaccessedorinQuickLaunch.Selectthemostpreferableoptionsduringinstallation.
3. Similarly,runPowerShellfromtheStartmenu.SearchforitandyoucanjustpressEntertorunit.
4. Itiseasiertoaccesstheprogrambyusingashortcutonthedesktopandusingaquicklaunchforconvenience.
5. Inaddition,usethePowerShellprogramwhichisalsotheTerminalprogram.
6. InthePowerShellprogram,initiatepython.Justlikeintheotherterminalprograms,yourunprogramsbytypingthenameandthenpressEnter.
1)Incasethepythoninstalledisnotresponsive,downloaditagainand
installitafreshfromthefollowinglinkhttp://python.org/download.2)ThebestversionisPython2.7.5.ThelatestVersionmanynotbecompatiblewithsomeoftheprogramsyouwillneedtousehere,therefore,don’tgoforPython3andanyother.3)IncaseyoudonothaveAdministrativerights,youwillbebetteroffusingtheActiveStatePython.4)ChecktoensurethatthePythonprogramjustinstalledisingoodworkingcondition.Ifnot,usePowerShelltotryifitcanbeactivatedbytypingthefollowing:
5)ThenclosePowerShellandrestarttheProgramtoconfirmwhetherthePythonnowruns.Incaseitisnotworking,youwillneedtoRestartyourcomputertointegratealltheprograms.
7. Next,exitPowerShellbytypingquit()followedbyEntertomoveoutofpython.
8. Checkiftheinitialprompthasbeenretainedevenbeforeyoutypedpythonintheprogram.Incaseitisnotthere,seektosolvethebugintheprogram.
9. InthesamewaylikeTextWranglerwhichisalsoatextEditorlikePowerShell,findouthowyoucanmakeadirectorydirectlyinthePowerShell(Terminal).10.Similarly,trytochangeintoadirectoryinthePowerShell(Terminal).11.Moreover,findoutifyoucanbeabletocreateafileinthisdirectoryusingfile,SaveorSaveAsandlocatethedirectorytowhichitwillbestored.12.Also,whileinthePowerShell(Terminal),tryswitchingwindowsusingyourkeyboard.Searchitupifyoufindaproblemfiguringitout.13.InthePowerShell(Terminal),trytolistthedirectoryjusttocheckifthenewlycreatedfileisinthedirectory.
Thewordterminalasusedinthiscontentreferstoeitherthe“Shell”or“PowerShell”inthisbook.
Warning
Mostofthetime,installingPythoninWindowsmayfaceafewchallenges.Itmayfailtogetconfiguredtotherightpath.ThiscanbesolvedbytypingthefollowingtextinthepythonPowerShell
Then,eitherRestartthePowerShellorthewholecomputersoasitgetsfixed.
Windows:WhatYouShouldSeeJustbyopeningPythonThisiswhatyoushouldsee
Tofindhelp,Typehelp()followedbyenter.Thisiswhatyouwillsee!
ForthepreviousversionsofPython;thisiswhatyouwillseeastheoutput:
Itisstillcorrectifyouseedifferentinformationthanmine,butyoursshouldbesimilar.
PythononLinuxLinuxisauniqueoperatingsystemthatcomeswithaverydifferentwaysofinstallingprogramsonit.But,installinganysoftwareonanycomputerrequiresyourabilitytofollowinstructionsasdirectedbythesoftwareduringinstallation.DefaultsettingsarealwaysrecommendedandvarywiththeOStobeused.
MyassumptionisthatifhaveLinux,then,youprobablyunderstandhowtoinstallapackage.Thisishowthiscanbedone:
1. ThebesttexteditorinLinuxistheGedittexteditor.2. ItisinstalledusingtheLinuspackagemanager3. Placetheprogramgeditonthedesktopasashortcuttotheprogram
orpinitonthestartbuttonforeasyaccess.1)Rungedittoseewhethertheprogramisfullyconfiguredoritwillneedsomequickfixes.Ensuretheprogramhasbeensettothedefaultmode.2)Next,gettoPreferencesandselecttheEditortab.3)Then,editthetabwidthto4.4)CheckontheboxrepresentingthepartInsertspacesinsteadoftabs.5)EnsurethatAutomaticIndentationisturnedon.6)Similarly,gotoopeninthefilecontrolmenu,selectViewtab,then,check“Displaylinenumbers"toturniton.
4. Locateyourterminalprogram.5. ItmaybereferredtoasGNOMETerminal,Konsole,orxterm.6. TransfertheTerminaltoyourdocks.7. TryarunofyourTerminalprogram.8. Runpythonintheterminalprogrambytypingrequiredcommandand
pressingEnter.1)IfyourpythonisnotresponsiveormissinginyourTerminal.Downloaditaddressandinstallit.Itisrecommendedthatyoutrygettingpythonversion2andnot3.
9. Then,exitpythonbytypingquit()andpressEntertoexitfrompython.10.ThisshouldreturnyoutothepythonpromptbeforeyoutypedPython.Incasethisdoesnottakeplace,trytofixthebug.11.TrymakingadirectoryfromtheTerminal.12.Inaddition,trychangingintoadirectoryinTerminal.13.Createafileusingyoureditorandsaveitinthedirectorycreated.ThiscanbedonebyusingthefileandthenSaveorSaveAs.tothedirectoryrequired.14.Tryshiftingbetweenwindowstogettothedirectory.15.Confirminthedirectorywhethertheprogramcreatedislisted.
HowtofindsolutionsintheinternetTheinternetsearchengineisthebestplaceforyoutofindsolutionsonPythonprogramming.Mostofthechallengesmayhavealreadybeendoneandsolvedbypeopleandpostedonline.Hence,insomepartsinthisbook;Iwillfromtimetotimeprovidedirectiononhowbesttofindsolutionsonthesearchengines.
Thisisthebestwaybywhichyoucanbecomeanindependentlearnerinprogramming.Theabilitytotroubleshootandfindsolutionsshowsthepotentialofbeingagoodprogrammerinthenearfuture.Thisisthemaingoalofthisbook.AllowingyoutoexploityourpotentialandbecomethebestinPythonprogramming.
Googleisthemarketplaceforallthisinformation.ThankstotheWorldWideWebdevelopers.Youcanfindaresponsetoeverythingyouneed.
Forinstance,ifyouwanttodownloadPythonsoftware:
1. Gotohttp://google.com/2. Type:pythondownload3. Readthewebsiteslistedtofindthebestanswer.
AsamplescreenshotofthissearchonGoogleisattachedbelow:
Chapter2:InteractingwithPython
Tobeabletointeractwithpython:Itisimportantthatyouknowhow,when,whyandwhatcanbedone.Inchapterone,Iintroducedtoyouhowtoinvokepython.
Topromptthepythonprogram,typethetextprint“Hello,python!”;andpressenter.
Theoutputwillbeshownas:
Hello,Python!(Indicatedinblueinthescreenshots)Thiswillbeseenbelow:
Thisisthefirstprogramsuggestingthattheprogramisactiveandworking.
PythonIdentifiers
Anidentifierisanamethatcanbeusedintheidentificationofavariable,class,function,class,moduleorobject.Inmostcases,inNamingrulesinPython
1. Whenusingaclassname,alwaysstartwithanuppercaseletter.2. Allotheridentifiersmustalwaysusealowercaseletters3. Whenanidentifierstartswithaleadingunderscore,itisa
suggestionthattheidentifierisprivate4. Twoleadingidentifierssuggeststhattheidentifierisstrongly
private5. Endinganidentifierwithtwounderscoressuggeststhatthe
identifierislanguagedefinedwithaspecialname.
ReservedwordsinPython
Thisarewordswhichcannotbeusedasconstants,variableorkeywordsasanidentifierinPython.Thewordsarealwaysinlowercaselettersonly.Theyinclude:
yield globalwith fromwhile fortry finallyreturn execraise exceptprint elsepass elifor defnot continuelambda classis breakin assertimport andif LinesandindentationinPython
Pythonasaprogramdoesnotknowhowtoidentifyblocksofalgorithmsasablockofcodesforclassandsometimesfunctions.Hence,theonlywayPythonisabletoreadandunderstandyourprogramisbytheuseofblocksofcodescreatedbyindentations.
Thenumberofspacesintheindentsisnotfixed.Moreover,allstatementswithinthecodesneedtobeindentedinthesamelength.
Forinstance,seethefollowingcodecreatedinPython2.7
MixingtheindentationsinmostcasesbringanerrorinthepythonshellwhentheprogramisrunbypressingonF5keyorbyselectingrunfollowedbyrunmodule,eitherway,itisthesame.
MultiplelinesinpythoncanalsobeusedMostofthestatementsinpythonendupwithanewline.However,linecontinuationcanbeusedbytheuseofcharacters(\).Thisshowsthatthelineisacontinuationfromthepreviousstatement.
Forexample
However,whenthestatementsarecontainedwithin[],(),or{}typesofbrackets.Theydonotneedtheuseofthelinecontinuationcharacters.
Forexamples
UsingQuotationinpython
Onecanusesinglequotes(‘’),ordoublequotes(“”)andsometimestriplequotes(‘‘‘or”””)asawayofrepresentingstringliterals.Therulewiththeuseofquotesisthattheyshouldbethesamewhenbeingusedatthestartandattheendofthestring.
Thetriplequotesareoftenusedwhenspanningastringoverseverallines.
Checkouttheuseofthequotesbelow:
UsingcommentsinPython
Tobeabletounderstandyourprogram,onemayneedtomakecommentsinbetweenthecodesorevenafterthecodes.Thecommentscanbeprotectedfrombeingrecognizedascodesintheprograminavarietyofways.
Ahashsign(#)isusedatthestartofacomment.Theprogramwouldautomaticallyassumeeverythingstartingwithahashsign.However,whenitisused.Theruleisthattheallthecommentsmustnotbeusedasstringliterals,i.e.theyshouldnotbeplacedinsidequotes.
Also,allthecharactersthatareprecededbythehashsigntothephysicalendofthelinearerecognizedaspartofthecomment.Theinterpreterignoresthemautomatically.
Notealso,thatacommentcanbeplacedinthefollowingways:
1. Itmaycomeafteralineofcode2. Youcanalsocommentafterasintheshownbelow.3. Commentscanalsobeinmultiplelines,buteverylineneedsto
startwithahash(#)sign.
BlankLines
Blanklinesinpythonareignoredautomatically.Theycouldbeablanklinewithonlywhitespace.Theycanalsobeblanklinewithacommentusingahash(#)sign.Theyareallignoredbypython.
However,whendevelopinganinteractiveinterpreter.Ablanklinecanbeusedtoterminateamultilinestatement.
UsingmultiplestatementsonasinglelineTocreatemultiplestatementsonasingleline,asemicolonisused.However,thisisonconditionthatthenewstatementdoesnotrepresentanewblockofcodethatcaninitiateadifferentprocess.
Thesemicolonscanbeusedasfollows:
MultipleStatementGroupsasSuites:
WhentherearegroupsofasinglecodeexpressedassinglestatementsinPython,theyarereferredtoassuites.
Compoundstatementsinvolvingtheuseofwordssuchasif,def,while,class;requireaheaderlineandasuite.
Moreover,alsoimportantaretheheaderlines.Theystartastatementwithakeywordandtheyterminatewithacolon(:).Theyrequireafewotherlinessoastheycanmakeupasuite.
Hereisanexampleoftheuseofif,elifandelsetomakeasuite.
Note:theindentationasusedisimportant.
Insummary
InteractingwithpythonrequiresthatyoushouldbeabletocomprehendthebasicrulesforusingPython.Afullfunctionalcodewillrequirethattherightindentations,blanklines,colons,commentsandotherinteractingapproachesarecorrectlyapplied.
Chapter3:Boolean’sinPython
SimpleConditions
BooleanisatestorconditionalsystemfirstdevelopedbyamathematiciancalledGeorgeBoole.ThishasbeenderivedandusedinPython.Itissetasaconditionoratest.Inthischapter,simpletestswillbedonetoshowcomparisonofvalues.ThiswillalsobetranslatedtoensurethatyoucomprehendeveryaspectofthecomparisoninthehandlingofthearithmeticinPython.Usingthefollowingexamples,trythemoutinpythonandgettoknowwhathappenswitheachoneoftheminPythonShell.
Theconditionsasusedinthiscasecaneitherbeexpressedastrueorfalse.Theyarealsonotexpressedinquotesbecausethatwillchangetheirmeaningandoperationscompletely.ThereisaperfectexamplefortheuseofBooleanvaluesdevelopedinthe19thcentury.
TheapplicationofBooleansinpythonistheshortformofthenametobool.Thisisappliedintestsresultsfortheuseofexpressions:TrueorFalseconditionsortests.
Thisisthesimplehistory,howtheBoolean’sstartedandwhattheyrepresentinPython.
Simpleif,else,elifStatementsuseandapplicationinPython
Ifstatement
TherearevariousstatementsthatcanbeuseinPython.TheyareaperfectsetofconditionalexpressionswhichcanbeusedtoexpresslogicandprovidearesponseintheformofanoutputinPython.
Forexample,tryoutthisshortcodeandsaveitasluggage.py.Runittwiceor
thricebutchangingthevaluesoftheinput30,40andthen56.
Notethattheinputdeterminesthenatureoftheresult.
Iamprovidingyouwithscreenshotssothatintheprocessofwritingthecodesonyourprogram,youalsolearnandseehowtheprogramsissupposedtobeindentedandmanyotherapplicationscoveredpreviously.
Thesecondlineofthecodeisanifstatement.ItcanbeinterpretedtobelikeastorybeingreadinanEnglishbook.Whenitistruethattheweightoftheluggageisgreaterthan50,thenastatementoftheextrachargeismade.But,whenitisnottrueandthevalueislowerthan50,thendon’tdotheindentedpartofthecode:skiptheindentedpartsofprintingthechargevaluefortheextraluggage.
Ineveryoftheevents,whenevertheifcodehasbeenexecuted.Itmakesadecisiononwhethertoproceedwiththeindentedpartsornot.
Hence,thenextlinewillbeprintingthestatement,“thankyoufordoingbusiness”
Overally,theifstatementgeneralPythonsyntaxisexpressedasfollows
ifcondition:
Statement(s)block
Whatthisrepresentsisthat:Iftheconditionwillbeindeedtrueasstated,thenproceedtotheindentedstatements.But,iftheconditionsetisnotapplicableinthiscaseandnottrue,thenskiptheindentedstatements.
Formorepractice,letusconsideratellermachineinasupermarketwhichexecutesthefollowingcodeineverytransactionisconducts:
Thisisanifexpressionwithablockofindentedstatements.Theblockmayhaveasingleorseverallinesofstatements.Themainmeaningofthecodeisthatwheneverthebalanceoftheaccountgoestonegative.Itisreturnedto0throughaseriesofotherstepswhichwillbeabletotransfersomesomefromthebackupaccounttoensuretheaccountisalwaysat0(zero).
Thismeansthatwhentheconditionistrue,thenithasachoiceofdoingsomething.But,whentheconditionisfalse,thenithasnothingtodoandonlysay“ThankyouandGoodBye”
if-elseStatements
Thegeneralsyntaxforthisstatementisexpressedasfollows:
Ifexpression:Statement(s)else:Statement(s)Thestatementblockscanhaveasmanynumbersofstatementsastheycanbeincludedintheprogram.
Let’strytounderstandtheif---elsestatementsbylookingatthefollowingexample:
Createaprogrambelowinyourpythonandnameitenvironmental_cloths.py.Thenruntheprogramandseetheresults.Youcanalsoplayaroundwiththeinputvaluesas60and85respectivelytoseewhattheresultswilllooklike.
Youareexpectedtofinddifferentresultswithdifferentinputs.Hereisthecodeforyouapplication.
JustlikeIhaveexpressedinthepreviousexample,thiscodescanbereadlikeanEnglishstory.Otherwordssuchasotherwisecanbeusedinsteadofthewordelse,however,weuseshorterwordsinPythontoreducethebulkofwordinginprogramming.
Notealso,thatthecodehastwoindentedblocksofcode.Theaftertheifandaftertheelse.Thefirstblockistheifstatement.Theindentationisexecutedonlyoftheifistrueotherwise,nothinghappens.Next,whenitisfalse,theelseisexecutedaswell.Hence,whenusingtheif..elsestatement,onlyoneoftheheadingscanbeexecutedatanyone,whenifistrue,elseindentedblockisnotexecuted,butwhenifisfalse,thentheelseindentedblockisexecuted.
Chapter4:Boolean’sandConditionalexpressions
Mostofthemathematicalcomparisonscanbemadeinpython.However,theylackthesymbolismduetotheabsenceofthestandardkeysonalmostallthekeyboardsinexistence
Belowisarepresentativecodingforarithmeticsymbolsusedinmathematicsandpython.
Meaning MathSymbol PythonSymbolsLessthan < <Greaterthan > >Lessthanorequal
≤<=
Greaterthanorequal≥
>=
Equals= ==
Notequal≠ !=
Note:Thereneednotbespacebetweenthesymbolswhenusedinpython.
AlsonotethatasingleequalssignisusedforassigningvaluesinPythonaspreviouslycovered.Hence,whenusedintests,asecondequalssignneedstobeusedinPython.Itisannoying,isit?
Therefore,whenusingasingleequalsignfortestingforequalityinpythonandwhennotintendingtouseitforassigningvaluestoavariable;thiswillautomaticallygenerateanerror.
Testingforequalityneverassignvaluesandhenceneverneedyoutoplaceavariableontheleftofthedoubleequalsymbols.Mostoftheexpressionsmaybetestedforequalityorinequality(!=).Hence,nonumbersmayberequired,.
Usingthefollowingvalues,trytomakepredictionoftheresults.Eachlinecanbetestedonitsowninpythonshell.
x=6xx==6x==8xx!=8x=94==x4!=x'hi'=='h'+'i''HI'!='hi'[1,2]!=[2,1]
Note:Assignmentcannotbemadeusinganequalitycheck.Stringsarealwayscasesensitive.Moreover,orderisveryimportantinalllists.
Usingthisexample,tryitoutinPythonShell.
'b'>6
Often,whenthecomparisonisnotwhatisexpectedormakessense,anexceptionismadeforthecode.
TheinexactnessinPythonisnotacceptableespeciallywhenusingfloatvaluesandstrings.Thefollowingexamplescanalsobeused:0.3+0.4tobeequalto0.7.TrycreatingacodethatwillbeabletoexpressthefollowingexpressioninthePythonShell.
Aperfectpracticalexamplecanbeexpressedusingthefollowingpaycodefornormalandovertime.Usinganindividual’sworkscheduleforworkinghoursfortheweekandregularwageforeveryhourworkedfortheweekandwithconsiderationofthehourlyovertime.
Whenthehoursworkedareover40,thentheyareconsideredasovertime.They
arethenpaiddoublethenormalrate.Thiscanallowustomakeapythoncodethatwillbeabletodothecalculationforthemoneythatispayableperemployee.
Thesetupforthefunctioncanbeexpressedasfollows:
Trytoreadthesetupforthefunctionasexpressedbelow:
Thiscodewillbeabletohandletwocases,whenlessthan40hoursoftotaltimeisworkedandwhenmorethan40hoursoftotalhoursworkediscovered.
Whenmorethan40hoursoftotalworktimeiscovered,then,anewvariablewillhavetobeintroducedcalledovertimeHours.Thiswillbeabletomanagetheamountoftimeworkedinexcessofthe40hourstotalworktimeandincludedinthetotalwageforthemonth.
Sincewearetrainingyouasaprogrammer.TrytoseehowthissolutioncanbereadinEnglish.
Then,trytorunthisprogramoutandseetheresults:
Usethisprogramsnamedwages.pyasanexampleofaprogramforthisexercise.
Thisprogramhasadoptedtheuseoffloatingstingspointformat.(StringFormatsforFloatPrecision)soastoallowtheuseofthecentsintheanswertotwodecimalplaces:
Inmostcases,thiswillbeabletomanagethenumericvaluesbutthiscanaccommodatethedecimalconversionsfromstringsviafloatsandnotintegers.
Alternatively,adifferentversionoftheexpressioncodeforthebodyofcalculatingweeklywagescanbeusedinthecodeusedabove.
Thisisjustageneralformulawhichwillbeabletomanagetheexpressionintheformulaandallowtheparameterstoaccommodatetheifstatement.Thesameproblemcanbesolvedusingmanyotherwaysinwaythatwillstillprovideyouwiththesameoutput.
PracticalExercise
AssignmentOne:Graduationlist.py
Developaprogramnamegraduation.py.Thisprogramshouldbeabletoclassifystudentsonthebasisofhowmanycreditstheyhave.Theprogramshouldbeabletoprintastatementonwhethertheyhaveenoughcreditstobeabletograduate.AtKenyattaUniversity,itisarequirementthatoneneedsabout120creditssothattheycanbeabletograduate.
Assignment2:HeadorTailsExercise
Developaprogramandnameitht.py.Htreferstoheadsandtails.Thecodeneedstointroduceafunctionflip () ,thiswillrepresentasingleflipofacoinwhichwillbeabletorepresenteithertheheadoratail.Youtrycomeupwitharangeofnumbersbytheuse0or1witharandom.randrange(2),Also,usetheif---elsestatementthatwillallowtheprintingofheadswhentheresultiszero(0)andtailswhentheresultsis(1).
Createasimplerepeatloopwhichwillcallflip()12timessoastotryyourcodeifcangeneratearandomsequenceof10headsandtails.
Chapter5:Useofif–elifstatementsinmakingMultipleTestsinPython
Whenonewouldliketocreatemorethantwodistinctcasesandtheconditionshaveonlytwopossibleconditionswhichcaneitherbetrueorfalse.Theonlydirectchoicemaybebetweentheothertwooptions.Forinstance,whenonehasabout20questions,youcanbeabletomakemorecasesbyuseofmorequestions.Whentherearemorethantwochoices,asingletestcanbeusedtoreducethepossibilitiesandothertestsaddedwillbeabletolowerthepossiblefurther.Statementswillberequiredtobeplacedinaindentedstatementblockandanotheraddedchoicewillbeanextraifstatementtotheblock.
Forinstance,ateacherwouldliketomakeaconversiontablefornumericalmarkstogrades(A,B,C,D,EorF).Themarkslimitsare90,80,70,60respectively.Hence,thiscanberesolvedveryeasilybystatingallthepossibleoptionsintheelseclause:
Itisnotmandatorythattheindentationbeusedforeverycasewhenusingtheif--elseexpression.Itisindeeduniqueandmustbestrictlyfollowedinthiscase.
However,theindentationcanbeclearedusinganalternativeif…elifclause.Theelifcombinesboththeifandelseclausetobecomeanelifblockinthepythoncode:
Seethiscodebelowandnotetheindentationappliedinthiscase.
Thesyntaxappliedinthisuseofif,elif–elseclauseisillustratedbelow.Thishelpsyou
Notethatalluseofif,elif,andthefinalelseareallalignedononeline.Thenumberofeliftobeusedisnotlimitedwitheveryofthelinefollowedbyanindentedblock.
Whathappensisthatoneoftheindentedblockwillbetheonetobeexecuted,whenitistheonethatcorrespondstothefirsttrueconditionssetusingtheifstatement.Otherwise,whenalltheconditionarefalse,thefinalelsewillbeexecuted.
TheuseofifandelifisanimportantformsofpythonContraction.Careneedbeobservedwhenusingthecontractedformofpythoncodes.Itissupposedtowrittenaselifandnotelseif.Thegradingmarks.pyisagoodexampleoftheuseofthiscodeillustratedabove.
Alternativesyntax
Theotherwayinwhichtheifstatementcanbeappliedisbytheuseoftheif-elif-andremovingtheelsestatementinthecode.Thissuggeststhatthesyntaxif-elif-elseismodifiedsothatthefinalblockofcodewithelseisremovedoromitted.Thisisthesameasthenormalifstatementthatdoesnotincludeanelseinitscode.Thisallowsforthenoblockofcodetobeexecutedandonlyoccurswhennoneoftheconditionsinthetestsistrue.However,whenanelsecodeisincluded,oneoftheindentedcodehastobeexecuted.Intheabsenceoftheelsecode;atmostoneofthecodeastobeexecuted.
Thiscodewillonlybeabletoprintalinewhenevertherewillbeaproblemwiththesuitcase.
Hereisanexampleofthecode:
PRACTICEEXERCISE
SignExercise
Developaprogramandsaveitasidentity.pytobeusedtocollectnumbersfromclients.Printoutthenumberandcategorizeitaspositive,negativeorzero
GradeExercise
Writetheprogramgradingmarks.pyandsaveitnowasgradingmarks2.py.
MakemodificationofthepythoncodesoastohavealettergradefunctionthatmakestheoppositeofthegradesstartingfromF,E,D,…A.
TrytorunyourcodeandmakedifferentinputstoensurethatyourcodeisworkingandprovidingyouwiththerightoutputinIdle.
WagesExercise
Similarly,makemodificationofthewages.pyandsaveitaswages1.py.However,ensurethatyoucreateaproblemthatindicatesthatpeoplearepaiddoublethemoneyforanyhoursworkedabove50hoursperweek.Thiswillshowthattheygettobepaidnormalratewithinnormalhoursfor40hoursaweek,and$1.5forhoursworkedextraof40butless50hoursanddoubleanyhoursworkedabove50hours.
Thiscanbeexpressedasbelowforatotalof:
10*40+1.5*10*20+2*10*5=$800.
Runyourprogramseveraltimeandmakemodificationstoensurethatitprovidesyouwiththerightcalculations.Usecommentswhereappropriatetohelppeopleunderstandyourcode.
Chapter6:UseofNestedControlflowstatementsinPython
BynowIbelieveyouarebecomingconversantwiththeabilitiesandpotentialofPythonlanguage.Itcanbeappliedinavarietyofwaysassimplestatementsandaswellascomplexorcombinedstatements.Onesuchexampleiswelldemonstratedintheuseoffor-ifandelsestatements.
Inthiscasenow,notethatforandifstatementscanbenestedinsideeachotherinanindentedblockofcode.Forinstance,fromaseriesofvalues,onecanbeabletoonlyselectpositivevaluesfromamixofnumericalinanarbitrarylistofnumbers.
Forexample.Usingthefollowingcode,itiseasiertoselectonlypositivevaluesfromamixofnumbers:
Justforamoment,trytoreadtheprogrambyfollowingthecommentsprovidedinthecode.Usingahumaneye,youwillbeabletoselectthenumberscarefully,butusingacomputer,thiswillbemadesystematicallycheckingeverynumberconsistently.Usingtheifstatement,everynumbercanbecheckeddeterminewhetheritcanbeprinted.
Thiscanbeobservedbelow:
NestingofthestatementsasintheuseofIfexpandsthepossibilitiesof
applicationsofLoops.Thiswillallowyoutobeabletousedifferentthingsinloopsandallowingconsistencyanddecisionmakingbetweenalternatives.
Besidestheifloops,therearealsothewhileloopswhichalsoworkwiththeifstatements.Nestingifstatementsandthewhileloopallowsyoutobeabletomakefarbetternestedprograms.
Pythonscanbeusedtoexpressgraphicalinterpretationofresults.
Forinstance,whenaballoonisreleasedandallowedtobouncewithinaroom,thiscanbeexpressedinPythontoexpressestherandomnessoftimesitwillbounceofftotheedgesoftheroom.
ThiscanbeallowedtooperatefromrandomlocationswhichcanbeappliedinPython.Theprogramcanberuninpythonshell.
Findasampleprogramthatcanbeusedtoexpressabouncingballoon.
bounceBall(-3,1)
Thisparameterprovidestheamountandshapeofmovementoftheballoonwhenbouncingineveryoftheanimation.Othervaluescanalsobeexpressedinshellandmagnitudeoflessthan10valuescanbeused.
Animationsbeforetheuseandapplicationswerepurelyscripts,onewasrequiredtodefinethedirectionandhowmanymovestobeconsidered.However,thedirectionofeverymotionmaychangewitheverybounce.Hence,inpython,thegraphicsobjectsshapescombinedwithacentralanimationstep.
Thiscanbeexpressedinthefollowingexamplecode:
shape.move(dx,dy)
Theuseofthevalues,dxanddyallowsthevaluestochangeastheballgetstotheboundary.Usinganexample,abouncingballoonmaygettotheleftsideasitismovingtotheleftandup.Thebouncingeffectwillhaveimpactonthenatureofthehorizontalmovementbuttheballwillkeepwithitsupwardmotion.AreverseeffectinthemotionofthehorizontalmovementcanalsobecapturedinPython.Thisallowsthebouncingballoontochangehorizontalshiftandhencethenegativesigntobeusedincodingwillbethereverse.Thiscanbeexpressedasbelow:
dx=-dx
Inthiscase,thevalueofdywillnotchange.However,thismaynotbethecaseineveryoftheanimationstepsinceitdoesnothappeneveryothertime.Thisthereforeprovidesfortheuseofifstatement.Thecenteroftheballooncanbeestimatedusingthecoordinateswhichisexpressedintheformofxandy(x,y).ThelowestpointthebouncingballooncanreachcanbeexpressedasxLow.
ThevalueofxLowshouldalwaysbegreaterthan0whilethevalueofedgeofthewindowisalsoatacoordinate0.Otherwise,atthisposition,thevaluesoftheballwouldbehalfwayofthescreen.Thexcoordinateofthecenteroftheballoonalsoneedstobethelengthoftheradius.
Theprocessofanimationtakesplaceinsmallstepsandthisispossiblebyallowingtheballtotakeonefirstsmallandquickstepofwhereitneedstogo(xLow),theballcanthenalsobereversedtotheoriginalpositionwhereitbelongs.
ThereareassociatedboundingvariablesthatcanbeusedtoexpressthebouncingvariablesxHigh,yLowandyHigh,whichrepresentstheradiusawayfromtheedgeintheformofcoordinatesandsameconditionstoassessthepossiblebouncingoffeachofthepossibleedge.Onecoordinatewillautomaticallyreverseinwhicheverwayaslongasoneoftheedgeishit.Thiscodecanbeexpressedasfollows:
Thiscanalsobeexpressedusingtheelifsentencestructure.Thiswillallowfortheextratesting.Thiswillimplythatifisindeedtruethatx<xLow,then,itmaybeimpossibleforittobetrueinthecasewhenx>xHigh.Therefore,bothtestsarenotneededtogether.Theuseoftheelifclausewillalsoprovideforeliminationoftheunnecessarytestswhenbothxandyistobeused.
Themiddleifshouldnotbechangedtomakeitanelifasusedinmanyothercases.Thisisbecausethereisapossibilitythataballcanreachacornerandtherefore,itmayrequirethatbothdxanddyshouldbechanged.
Avarietyofaccessmethodsforgraphicsarepresentthatcanbeusedusingdifferentshapessuchascircleswhichcanbedefinedbydescribingthecentrepoint.
TheycanbeaccessedbyusinggetCenter()method.Thiswillbeabletogenerateacloneofthepointswhichcanbereturned.EverycoordinatecanberetrievedbyusinggetX()andgetY()criteria.
ThismaybeanewfeaturethatcanbeappliedinthedefinitionofthecentralfunctionofabouncingballooninaboxbounceInBox.
Thisanimationwillbeabletodeveloparepeatloopwhichcanbeaccomplishedthroughaseriesof600steps.
Thiscanbecapturedinthisexperiment.
Thiswillmoveaballoonwhilebouncingfromanypointwithinarectangle.This
iswhatisexpressedinthefunctionofthecode:getRandomPoint.Thisfunctionallowstheuseofrandrangefunctionderivedfromthemainmodulerandom.
Parameterswithfunctionsrangeandrandrangeexpressestheendwhichhasbeendefinedinthepastandwhichisthelastvaluethatisactuallydesired.
Thefullprogramthatwillallowonetoanimateacompleteprogramthatwillbeabletoshowarepeatingbouncingballoon/ballisasexpressedbelow.Notethatthereistheuseofthefunction,bounceInBoxandgetRandomPointtoastheprogramtobecomplete.
Thesearealsonottheonlyfunctionsthatcanbedone.Noteverythinghasbeendescribedasdemonstratedinthecodebelow:manyotherthingswillneedmoreresearchtounderstandhowtheyfunction.But,theycanbeusedtogethersothataprogramwillbeabletofunctionappropriately.Thisprogramwillbeabletoshowaballbouncingoffthesidesofthewindow.
PracticalExerciseWriteaprogramexcellent.pythatwillhaveafunctionprintShortintheheading:Theprogramshouldbeabletoreadalistofstringsandthenitshouldbeabletoprinttheonewithatmostthreecharacters.
Testtheprogramdevelopedusingavarietyifhintstodeterminethelenoffunctions.
Thisshouldbetestedinthepythonshellinteraction.
Thiswill;havetostartwiththeline>>>EvenPrintExerciseDevelopaprogramandnameitgood.pywithafunctionprintEvenandheading:Usedifferentnumbersandensurethatitwillbeabletoprintevennumbers.Theprogramwillbesimilartothisone:
EvenListExerciseJustlikeabove,createanotherprogramandnameitgood2.py.ThisshouldbeabletoselectonlyevennumbersusingthefunctionchooseEven(nums)Writeaprogrameven2.pywithafunctionchooseEvenwith
heading:
Testthefunctionandconfirmwhetheronlytheevennumbersarechosenfromthelistrequired.
UniqueListExerciseCreateanewprogramnamedcrazylib.pywhichcanbeusedingettingthekeysusingthegetKeysfunction.Theprogramwillbeabletocreatealistofeveryoccurrenceofkeysfromacuedevelopedinastoryformat.Thekeyswillbedevelopedintheorderinwhichtheyappearinthelist.However,theywillhaverepetitions.Theoriginalversionusedtogetskeysanddeletingeveryduplicateinthedataallowingtheformationofsetsfromthekeys.Theonlychallengeinthatthesetsmaynotbeordered.Consequently,whenthe
programiteratethroughthecodes,theorderofthecueswillbearnoresemblancetotheorderinwhichtheyoccur.
Copy madlib2.py to madlib2a.py ,andaddafunctionwiththisheading:
OnecanusetheBooleanoperatorsinforcheckingofmembershipinasequence:
Itcanalsobeusedwith not ,as notin ,tomeantheopposite:
Hence,whatyoucannotehereisthattheworkisintwoforms:
1. Thisdeterminesanitemthatisinthesequence2. Thisisanitemthatisnotinthesequence
Tobeabletomakethisasuccess.Oneneedstomakesurethatthelistisinorder.Asyntaxcanalsobeusedtoappendelementstoanewlistswhichmayormaynotbeinthenewlist.
AfterusingtheuniqueListfunction,onecanalsoreplacethelastlineofthegetKeyssothatitcanalsousetheuniqueListsoastoremovetheduplicatesinthekeyList.
Trytocreatethisandrunittoensurethatcuesvaluesareinorder.
Chapter7:CompoundBooleanExpressionsinPython
Perhaps,thiscanbebestexpressedusingvalidexamples.Letusconsiderthiscasebelow:
ForonetobeeligibleforgraduationfromauniversityinUS,itwassetthatstudentsneeded120creditsandatotalGPAofminimum2.0.
UsingPython,createaprogramthatcanbeusedtoselectstudentsthatwouldbegraduand’sfortheyear.
Thissuggeststhatthiscanonlybetruewhencreditswillbeequaltoorgreaterthan120.
WhileGPAwasalsogreaterorequalsto2.0.
Agoodprogramwilllooklikethis:
Applicationofcompoundexpressions
Thiswillshowthatacompoundconditionwillbetrueifbothoftheconditionsaretrue.However,itwillbeseenasfalsewhenatleastoneoftheconditionsisfalse.
Exercise
Previously,wehaddiscussedtheuseofifandelifstatementsincaseswherebothtestswheretheywillappearinthesameblockwhentheconditiontobeappliedwastrue.
However,thiscanbestatedinamucheasierwayasshownbelow:Forinstance,ifx<xLoworx>xHigh,switchthesignofdx.ThiscanbetranslateddirectlyintoPython:
Theuseofthewordorcreatesacompoundcondition:
Itisrecommendedthatmostofthecomplicatedtestscanbeenshrinedinsideafunction.
Itisoftenconvenienttoencapsulatecomplicatedtestsinsideafunction.Thinkhowtocompletethefunctionstarting:
Arectangleisdefinedbytwodiagonallyoppositepoints.Thisishowarectanglecanbeprepared.ThetwocornerpointsaredefinedbythefunctiongetP1andgetP2.Pythoncallsthepointsobtainedaspt1andpt2.Thevaluesofthepointscanbeexpressedinthecoordinateofxandyofpt1,pt2.Similarly,thepointcanalsobeexpressedinthepointformofgetX()andgetY().
Justincaseweintroducevariablesforthexcoordinatepointsofpt1,point,p2.Thesamecoordinatescanalsobeexpressedasend1,va1andend2.Therelationshipbetweenthetwocoordinatescanbeexpressedusingmathematicalconcepts.
Forinstance,thiscanbeexpressedas:
end1<=val<=end2
However,thismaynotbesufficienttoexpressthepositionofthecorners.Itisexpectedthatthecornerspointsaresupposedtobediagonallyopposite,andthesecondcoordinatesalsoneedtobehighcomparedtothefirstpoints.Forinstance,end1maybe300;end2maybe150,whileva1maybe180.Notethat
theva1isbetweenthetwocoordinatesofend1andend2.Thesevaluescanbesubstitutedintotheexpression.
300<=180<=150
Thisexpressionisfalseandthevaluesof150and300willneedtobereversed.Thiscanonlybeacomplicatedsituation.Alsothisisanissuewhichmustberevisitedforboththexandycoordinates.ThesolutionthiscanbesolvedusinganewfunctionisBetweentohandleonecoordinateatatime.IntroduceanauxiliaryfunctionisBetweentodealwithonecoordinateatatime.
Thisexpressionmayonlybetruewhentheoriginalexpression,end1islessofequaltova1andisalsolessorequalstoend2.Thiswillbetrue.Thereisalsoalikelihoodthatthecasemaybereversed.ThistwooptionscanbecombinedastwouniquepossibilitiesusingBooleanconnectorsandandor.Thiswillmaketherelationshiptrueinoneoftherelationshipandusingor,thiswillbetherightconnective.
Therefore,thecompletecodeinpythonthatwillbeabletofunctionherewouldbeexpressedinthefollowingways:
Acorrectbutredundantfunctionbodywouldbe:
Asatechniqueofunderstandingyourcode:trytoextractthemeaningofthecodebyinterpretingthecodetoEnglish.
ThismeansthatifthestatementisTrue,returnTrue.Similarly,iftheconditionisFalse,returnFalse.Inbothcondition,asdescribed,thesamevalueswillbereturnedassetoutinthetestconditions.
Summary
Itisnotarequirementthatyouneedanif-elsestatementsothatyoucanbeabletochoosebetweenTrueorFalsevalues.ThiscanbeuseddirectlyusingtheBooleanexpressionsasdescribedbefore.
Similarly,otherexpressionswhenusingthecompoundexpressionsasinthiscase:
end1<=val<=end2
Themaincharactersareend1andend2.Thisissimplyastandardmathematicalsyntaxwhichcanbeusedinchainingcomparisons.Thenumbersofcomparisonscanbechainedusingtheseexpressionsusingapproximatenotations.NotealsothatthiscanonlybesuccessfullycodedinPythonunlikeotherprogramslikeJava,andC++.
Theycanalsobetranslatedinwaysthatcanbereadinmanyothercommonlanguagesasshownbytheexpressionbelow:
end1<=val
val<=end2
Ontheotherhand,anauxiliaryfunctionisBetweencanalsobeused.ThisisanisInsidefunction.TheisBetweenfunctioncanbeusedtofindthevaluesofthexcoordinates;andalsotocheckforthevaluesofthewhycoordinatesaswell.
Thetwoquestionscanbecombinedandthetwopointmayberequiredtobebetweenthesidesandbetweenthetopandbottom,similarly,therightconnectorstobeappliedisand.
But,howdoyoucompletetheisInsidemethod?Probably,youwillneedtofindthisout.Findoutmoreinformationfromthelinkbelow:
http://anh.cs.luc.edu/python/handson/3.1/handsonHtml/ifstatements.html#id16
Alsonotethatwhenyouwanttosolveforanoppositecondition.InmanycasesborrowingfromEnglish,awordnotisintroducedintheexpression.
Ifapointisnotinsidetherequiredpositionsuchasnotinarectangle,youwillbepromptedtostatethatthepointisnotinsidearectangle(rect).Thisconditioncanalsobeappliedinthiscase.
Therefore,thisanotcondition.
ItisonlyTruewhenconditionsetisFalse.ItisalsoFalsewhenconditionisTrue.
Aprogrambelowisanexampleofcreatingvaluesinsidearectangleandisreferredtoasselectbutton.py.
ThisisacompleteprogramthatappliestheuseofisInsideexpressionasasimpleapplicationforselectingcolors.Donotcaresomuchaboutthelengthsoftherectangles.
Anumberofeffortscanbedonetoensurethatthecodecanbeshortenedtoensurethatsmallrectanglescanbeusedinthiscaseandmakeitamorepowerfulcode:
ThisprogramappliestheuseofisBetweenandisInsidewhicharediscussedbelow:Thisprogramsmakesmakecoloredrectangleswhichcanbeusedasbuttonsandwhichcanalsobeusedaspicturecomponent.Thecodethathasbeenusedincreatingtherectangleissimilarandisinsideafunction
makeColoredRect.ThisisagoodexampleforuseofgraphicaltoolsinPython.
Thecodethathasbeendevelopedisquitelongandisenshrinedwiththegraphicalcodesfordrawingpicturesandbuttonsandhassectionswithqueriesforaskingtheusetoselectthecolorsforapicture.Youwillalsoobservethecodeshaveanif-elif-elsetesttocheckonwhichbuttonshavebeenpressedandsetthecolourofthepictureelementascommandedbytheprogram.
TheonlynewaspectwiththisprogramwillbetheuseofthelongstatementsisInsideasshownbelow:
Pythonisaninteractiveprogramthatwillbeabletoreadthestatementsastheycontinuetothenextlineevenwhenthereisanunmatchedpairofbracketsandparenthesis.Itisrecommendedthatwhenyouhavealonglinethatwillbeable
torunoverthescreenorpaper.Thisshouldbecontinuedtothenextline.
Tomakeafinalcharacteronalinewithabackslash(\)willbeusefulsinceitsuggeststhatthelinecontinuestothenextline.Thisisthebestwayofmakingyourworkneatsothatalmostallthestatementswillbeabletofitintothesameline.
Inaddition,thiswillalsobethebestwayofmakingyourcodessimple.UnlikePython,manyotherprogramswillrequireaspecialwayofterminatingalinesuchas‘;’whichservesascommandfortheprogramnottopayattentiontothenewlinescreated.InsomecasesinPython,anextraparenthesiscanalsobeusedanditwilldonoharmtotheprogramasshownintheaboveexampleusingtheisBetween.
PracticalExerciseYouareeligibletovieforaUSsenatorandUSRepresentativepositionwhenyouareatleast30and25yearsoldrespectively.Inaddition,youmusthavebeenaUSCitizenforatleast9and7yearsrespectivelyforthesepositions.
Writeaprogramandcallitcongress.pytoobtaintheageandlengthofcitizenshipfromtheusertocontestforthetwopositions.
Enhanceyourprogramsothatyoucanbeabletoobtaintheage,lengthofcitizenshipandprintoneofthestatementslistedbelow
1. YouareeligibleforbothsenateandrepresentativeandSenate.2. Youeligibleonlysenate3. Youareineligiblerepresentative.
Chapter8:PythonDataVariables(Numbers,Lists,Tuples,StringsandDictionaries)
Variablesarereservedmemorylocationsinpythonwherevaluescanbestored.InPython,youareallowedtocreateavariablewhichyoucanreserveinthememory.
Inthebasisofthetypeofdatainputonpython,theinterpreterwillbeabletoprovidememoryandmakeadecisiononwhetheritcanbestoredonthememoryreservedfortheoperation.Hence,whenyouassignadifferentdatatypetospecificvariablesasyoudecide,youwillbeabletokeeptheintegers,decimalsandorcharactersinthisvariable.
Howdoyouassignavaluetoavariable?
Anequalsignisusedasanoperandforassigningvariabletoaname.TheoperanttotheleftoftheequalsignisreferredtoasthenameofthevariablewhiletheoperandtotherighthandsideisthevalueofthevariabletobestoredinPython.
Nameofvariable=Valueofthevariable
Thiscanbeshowninthefigurebelow:
Whenthiscodeissavedandrun.Thefollowingresultsareshownintheoutput.
Itisasimpleprocess.Justtypeinyourpythonprogramthetextasprovidedanditshouldofferyouthesameoutputasshownintheexampleabove.
Therearevariousdatatypesthatcanbeusedinpython:
Theyinclude:
1. Numbers2. Strings3. Lists4. Tuple5. Dictionaries
NumbersinPython
Youcancreateanumberasanobjectwhenyouassignavaluetothem.Justlikethenameandvalueofthevariableoperandsarestated,theycanbeusedalsoforassigningnumbers.Forinstance:Var1=2
Var2=4
TypesofnumericalsupportedbyPython
Pythonbestworkswiththefollowingnumericals
1. int(recognizedasintegers)2. long(longintegers[arerepresentedashexaoroctadecimals])3. float(floatingpointrealvalues)4. complexnumbers
Examples
Int=10,100,-792,-0x250,0x75
Longnumbers=51924576L,0122L,0xDEFABCGDRT,53267687675L,-05238675443L
Float=0.0,14.90,-21.9,32.3+e20,-90
Complexnumbers=3.14j,45.j,9.322e-36j,0.876j
Pythonstrings
AstringisacontiguoussetofcharactersthatareplacedinbetweenthequotationmarksForexample:
Whatdoesthisprogramdo?
Seethecommentsintheprogram:
Theoutputwithrespecttothecommentsinthesameorderisasshownbelow:
Formorehelponstringsonpythonforusingclasses,functionsanddata,justtype[help(“string”)orhelp(‘string’)andthenpressenter]inthepythonshell.
Afulllistonhowtheclassescanbeimplementedwillbeprovidedforyoutofollowandhowtheycanbeapplied.
PythonLists:
Pythonlistsareveryvariableanduseincompounddatatypes.Alistissimplyaanumberofitemsthatareseparatedbycommasandenclosedwithinsquarebrackets([])Forexample:
Runningthisprogramwillproducethefollowingoutputintheorderofthecommandprint
Pythonhasaninteractivecommandforhelponlists.Justtype[help(‘list’)orhelp(“list”)followedbyenter]inpythonshell.ThiswillprovidealistofallformsofclassesthatcanbeappliedonlistsPythonTuples
Thisisanotherformofasequencedatatype.Itisverysimilartothelistsinpython.Italsoconsistsofvaluesthatareseparatedbycommas.Theyarehoweverenclosedbyparentheses().
Theyareoftenconsideredasreadonlylists.
Outputsoftheabovecodeintheorderoftheprintcommandareasfollows:
Forhelpontuples,justtype[help(‘tuple’)orhelp(“tuple”)followedbyenter]inpythonshell.ThiswillprovidealistofallformsofclassesthatcanbeappliedonlistsPythonDictionary
Thesearehashtabletypesvalues.TheyareassociativearraysorahashwhicharesimilarlyfoundinPerlandconsistsofkeyvaluepairs.
Examplesofpairsincludethefollowingvalues:
Theoutputisexpectedtolooklikethiswhenthisprogramisrun:
Datavariablesapplyinalldatacodesdevelopmentandunderstandinghowtheyworkandoperateisveryessentialinlearningprogram.
ConnectionbetweenListsandDictionaries
Itispossibletoworkwithbothlistsanddictionariesandchangingbetweenlistsanddictionariesandviceversa.Thisisacommonapplicationformostoftheprogrammerandsometimestheyhavetointerchangethedatatypesespeciallywhenworkingwithdatabaseswhichwillbelearnedlaterinthisbook(Chapter12).ThisisastrengthinPythonthatcanneverbefoundinanyotherlanguagesinceithasthisfunctionality,thatiswhyPythonisreferredtoasaninteractivelanguage.
Letusconsiderthefollowingexampleofadictionary:DistheDictionaryandListhelist.
wecouldturnthisintoalistwithtwo-tuples:
NotethatboththeDandLhavethesameinformation.Itcanalsobedescribedthattheirentropy(organizationandarrangementofeachword)isalsothesame.But,itshouldbenotedthatsometimestheinformationmaybehardertoberetrievedwhenasalistcomparedtoadictionary.
WhenwewanttofindvaluesinKey’s,wewillhavetofirstgothroughthetuplesofthelistscomparethecomponentsofthelistwiththekeys.Thiscanbewellperformedwhenusedasadictionary.
ListsfromDictionaries
Itisveryeasytodevelopalistfromadictionary.Thisisachievedbyusingthefunction(items(),keys(),andvalues().
Justthemethodkeys()willbeabletocreatealist.Thiswillplainlyconsistofkeysofthedictionary.Inaddition,values()willbeabletomakealistofvalues.Moreover,items()canalsobeusedtocreateoflistofitemsmadeof2tupleswithkeysandvalues(keys,values)-pairs:
However,whenamethoditems()isusedinadictionary,wemaynotbeabletogetalistback.But,wecanbeabletousetheitemviews,theitemviewswillbeconvertedtoalistwhenusedwithalistfunction.Noinformationwillbelostbyconvertingadictionaryintoalist.
Itisalsopossibletoreturntotheoriginaldictionaryfromtheitems(),evenwhenformedasalistoftuples,theyhavethesameentropy.However,theeffectivenessofthesameapproachesissimilar.
Therefore,dictionaryalsoservesasanefficientmethodtoaccess,replace,changeandvaryelementsofthedictionary.However,inlists,thesehavetobecodedbyaprogrammer.
TurnListsintoDictionaries
ThelistscanalsobeturnedintoPython;iftheselistssatisfycertainconditions.Letusconsidertwolistscontainingdishesandothercountries:
Adictionarycanbecreatedthatwillbeabletoassignadishtoacountry.Thiscanbedoneusingafunctionzip().Thiswillbeabletojointhelistslikeazip.Thiswillbeabletoiterateoveralist.Thissuggeststhatwehavetowrapalist()functiononthezipsoastocalltogetalist:
Thecountryspecificlistsofdishesarenowcompletelyconvertedtoalist.Thisisalistoftwotupleswhichhaskeysandvalueswhichcanalsobeautomaticallybeconvertibletoadictionarybyusingthefunctiondict().
Theonlymysterywillbetounderstandtheuseofthefunctionzip()whenonelistislongthattheother.
Thisisnotcomplicatedeither.Theprogramwillbeabletoignoreanyextraliststhatmaynotbepairedinanyway.
Here,Switzerlandwillnotbepairedinthiscaseandwillbeignoredintheoutputaspresented.
Allinone
Normally,werecommendnotimplementingtoomanystepsinoneprogramming
expression,thoughitlooksmoreimpressiveandthecodeismorecompact.Using"talking"variablenamesinintermediatestepscanenhancelegibility.Thoughitmightbealluringtocreateourpreviousdictionaryjustinonego:
Thiscanalsobewritteninthisotherway:
Summary
Thedatavariablescomeinthefiveways:Theycanbeinformofnumbers,lists,tuples,stringsandfinallydictionaries.Eachofthemisveryuniqueandworkingwithpythonateverysingleprocessrequiresabasicunderstandingoftheirfunctionsandclasses.
Inpython,tobetterunderstandhowthiscanbeapplied.Youcanseekhelpfromthepythonbytypinghelp(‘object’)orhelp(“object”)followedbyenter.Thiswillprovideyouwithasolutiononhowanyofthevariablescanbeapplied.
Chapter9:BasicOperatorsinPythonforCalculations
Operatorsarethefunctionswhichcanbeusedinthemanipulationofthevaluesoftheoperands.Forinstance,letusconsidertheexpression5+15=20.Inthisexample:5and15arereferredtoasoperands,whiletheplussign(+)isreferredtoastheoperator.
Operators
Pythonlanguagesupportsthefollowingtypesofoperators.
ArithmeticoperatorsComparisonoperatorsforestablishingrelationsbetweenvaluesAssigningoperatorsforequatingvaluestoanameLogicoperatorfordeterminingthelogicbetweenvaluesoneithersideoftheoperators.MembershipoperatorsOperatorsforinfluencingtheidentityofobjects/values
Hereisalistofthevariousformsofoperatorsandexamplesonhowtheycanbeappliedinarealpythonalgorithmicdevelopmentscenarioinprogramming.Theyhavebeenlookedatonebyone.
PythonArithmeticOperators
Letisassumethatavariablenamed(a)hasavalueof5andvariable(b)holdsavalueof15,therefore:
Operator Description Example
+Sumsupthevaluesofthevaluesoneithersideoftheoperator.
a+b=20
-Givesthedifferenceofthetwovaluesoneithersideoftheoperator
a–b=-10
*Givesyouaproductofvaluesoneithersidesofthe
a*b=75
operator
/Providesadivisionofthetwovalues
b/a=3
%Dividesleftbyrighthandvaluesoftheoperandandgivesthevalueoftheremainder
b%a=0
**Makesthesecondvaluetheexponentialpowerofthefirstvalue
a**b=5tothepower15
//ThisisalsoreferredtoastheFloorDivisionInthisdivision,thedigitsafterthedecimalpointareremovedfromtheresultofthequotient.
OperatorsforcomparisonofvaluesComparisonoperatorsmakeacomparisonofthevaluestotheleftandrightoftheoperandandhelpsdefinerelationshipbetweenthevaluesassetbytheoperand.Theyarealsoreferredtoastherelationaloperators.Usethevaluesfor(a)and(b)asillustratedabove.
Operator Description Example
==Itsetsasaconditionforthevaluestotheleftandrightiftheoperandtobetrueonlywhentheyareequal.
Itisnottruewhen(a==b)
!=Itsetsasaconditionforthetwovaluestobetrueonlywhenthevaluesarenotequal
Sameasabove
<> Itsetstheconditiontobetruewhenthevaluesoftheoperandsarenotequal.
Itistrueonlywhen(a<>b).Theapplicationissimilartothesign
!=> Thisemphasizesonthe
valueoftheleftoperand.Whenithasahighervaluethantherightvalue,Itacceptstheconditionastrue.
Itisnottrueif(a>b)
< Italsoemphasizesonthevaluetotheleftoftheoperand.Whenthevalueislessthantherightvalue,itacceptsthesetconditionastrue.
Itistruewhen(a<b).
>= Thisisappliedonlywhenthevalueoftheleftoperantishigherorsameasthevaluetotherightoperand.Thisrecognizestheconditionastrue.
Itisnottruewhen(a>=b).
<= Ifthevaluetotheleftislowerthanorequalstoright.Thisenablestheconditionassettobetrue.
Itistruewhen(a<=b).
PythonforAssigningOperators
Operator Description Example
=Itassignsthevalueoftherighthandsideoftheoperandtothelefthandside.
c=a+b
+=AddAND
Thisoperantaddsvaluesontherighttoleftoperandandequatessumtotheleftoperand
c+=aisequaltoc=c+a
-= Itgetsthedifferencebetween c-=aisalsoc
SubtractAND
therightfromleftoperandandgivesthedivisiontoleftoperand
=c-a
*=MultiplyAND
Itsactionissameasabovebutthenasaproductoftherightandleftoperandandmakestheresultequaltotheleftoperand.
c*=aissameasc=c*a
/=DivideAND
Sameasabovebutmakesadivision
c/=aissameasc=cac=aandalsoc=c/a
%=ModulusAND
Sameasabovebutmakesfloordivisionandgivesaquotientsandequatesthequotienttotheleftoperand
c%=aisequivalenttoc=c%a
**=ExponentAND
Assignsanexponential(power)onoperatorsandequatestothevalueoftheleftoperand
c**=aissameasc=c**a
//=FloorDivision
Itcreatesadivisionofoperatorsandequatesthevaluecalculatedasequaltotheleftvalueoftheoperand
c//=aisexpressedasc=c//a
PythonMembershipOperators
Theseoperatorsevaluatemembershipofvaluesinasequenceinvariouspythondataformssuchasstrings,lists,ortuples.Thereareonlytwoformsofpythonmembershipoperators:
Operator Description Exampleis Itevaluatestobetruewhenthe
variablesoneithersideoftheoperatorsaresimilarorequatestothesameobject.Butitisfalse
xisy.
otherwise.notin Itbecomestruewhenavariable
inthesequenceisnotfoundandotherwise,becomesfalse.
xnotiny
PythonIdentityOperators
Thisonlyservestomakeacomparisonoftwomemorylocationsfortwodifferentobjects.Similarly,justlikemembershipoperators,thereareonlytwomembershipoperatorsasexplainedbelow:
Operator Description Exampleis Evaluatestotrueifthevariables
oneithersideoftheoperatorpointtothesameobjectandfalseotherwise.
xisy
isnot Evaluatestofalseifthevariablesoneithersideoftheoperatorpointtothesameobjectandtrueotherwise.
xisnoty
PythonOperatorsorderedlist
Thetablebelowrankstheoperatorsintermsoftheirprecedenceindescendingorder.
Operator Description
**Exponential(raisesonevaluetothepoweroftheother)
~Complement,
+plus
- unaryminus
*Multiply
/divide
%modulo
//floordivision
+Addition
-Subtractions
>> Rightshiftbitwise<< leftbitwise& Bitwise'AND'
^|exclusive`OR'andregular`OR'bitwise
<=> Comparisonoperators<> comparison
=comparison
<>==!= Equalityoperators=%==/=-=+=*=**=
Assigningvaluesoperators
Is,isnot Identityoperatorsinnotin Creatingmembership
operators
notorand Creatinglogicaloperators
Chapter10:OpeningandClosingFiles
Sincethestartofthischapter,wehavebeendealingwithbasicsoftryingtoreadandwriteinputsinpython.Thistime,Iwouldlikeustoexploretheuseofwritingandreadingrealfilesoutsidepython.Yes,pythonisaverypracticalprogramandonecanbasicallybeabletodoanythingaslongasheknowswhatexactlyneedstobedoneinPython.
Pythonhassimplefunctionsandmethodsthatenableonetobeabletomanipulatefiles.Thisisachievedbytheuseofthefileobjectsinpython.
Butbefore,wegettoit:
Itisfirstimportanttofirstdescribesomefewotherfunctionssuchasimport.HowdoyoubringinthefilefromadifferentdirectorytoPython?ThisishowitisachievedinPythonbyusingtheimportstatement:Importstatement.
Anypythonsourcefilecanbeusedamodulethroughtheexecutionoftheimportstatementfromsomeothersourcefileinpython.
Theimportfunctioncontainsthefollowingmodule.
Thefunctionimporthastobeplacedatthetopofthescript.
Themodulewouldthembeloadedonlyoncehowever,despitethenumberoftimestheimportfunctionsisusedinthescript.ThisallowstheprogramtopreventmultipleimportsofthefiletobeexecutedintheprogramYouwillnotethatwhenimportingafile,forinstance,aXMLfileconvertedasaCSVfile,first,ithastobeimportedbeforeanyexecutioncodecanbedefined.Thiswilldefinewhattheprogramwillbeabletodoonthefileimportedintopython.
Pythonhasinbuiltbasicfunctionsandmethodsnecessarytomanipulatefilesbydefault.Thefileobjectcanbeusedtodotheexecutionandmanipulationofthe
filesyouneed.
TheopenFunctionAfilehastofirstbeimportedbeforeitcanbereadandwriteinPython.EvenbeforeyouareabletoreadandwriteafileinPython,youwillneedtofirstopenituptoberead.Thisisachievedusingtheinbuiltopen()functioninPython.Thisfunctionallowsthecreationofanobjectasafilewhichwillthenenabletheexecutionofothersupportfunctionsassociatedwiththefile.
Theopenfunctioncomesasbelow:
Hereareparameterdetails:
file_name:isusedasstringthatcontainsthefilenameofthefilethatistobeopenedinpython.access_mode:Determinesthemodebywhichthefileisrequiredtobeopened.Itallowsforreading,writingandappendingamongothermodesavailableinPythonaswillbedemonstratedinthetablebelow.However,italwaysrecommendedapplyingthedefaultaccessmodeasread(r).Buffering:Thisavaluewhichcaneitherbezerooranyothernumber,often1isused.Whenthebuffervalueisfixedaszero(0).Nobufferingisappliedforthefilesbeingread.However,whenthebuffervalueisusedas(1),bufferingisappliedatthetimethefileisbeingaccessed.Always,aslongasthebuffervalueisanintegerandavaluemorethanone,thebufferingprocessisinitiatedinaccordancewiththesuggestedbuffersize.Butifthebuffervalueisnegative,thebuffersizeadoptsadefaultcharacteristic.
Modesofopeningfileisasdescribedinthetablebelow:
Modes Descriptionr Afileisopenedbutitcanonlyberead.The
readingstartsfromthestartofthefile.Thisisusedasadefaultmodesetting.
rb Thisallowstheopeningofthefilebutforreadingonlyinthebinarymode.Thereadingstartsfromthestartofthefile.Thisisusedasadefaultmodesetting.
r+ Thismodeallowstheopeningofafileforreadingandwritingatthesametime.Thereadingstartsfromthestartofthefile.Thisisusedasadefaultmodesetting.
rb+ Thismodeallowstheopeningofafileforreadingandwritingatthesametimebutinthebinarymode.Thereadingstartsfromthestartofthefile.Thisisusedasadefaultmodesetting.
w Allowsafiletobeopenedbutcanonlybewritten.Itallowstheexistingfiletobeoverwritten.However,anewfilewillbecreatedwhennoneofthefiledescribedexists.
wb Allowsafiletobeopenedbutcanonlybewritteninthebinaryformat.Itallowstheexistingfiletobeoverwritten.However,anewfilewillbecreatedwhennoneofthefiledescribedexists
w+ Allowsafiletobeopenedandcabbereadandwrittenatthesametime.Itallowstheexistingfiletobeoverwritten.However,anewfilewillbecreatedwhennoneofthefiledescribedexists
wb+ Allowsafiletobeopenedandcabbereadandwritteninthebinaryformat.Itallowstheexistingfiletobeoverwritten.However,anewfilewillbecreatedwhennoneofthefiledescribedexists
a Thisallowsafiletobeopenedandcanonlyallowappendingofnewinformation.Hence,thefilepointerwillbeattheendofthefileifitexistsanditispresentintheappendmode.Anewfilewillalsobecreatedifthefilementioneddoesnotexist.
ab Thisallowsafiletobeopenedandcanonlyallowappendingofnewinformationonlyinthebinary
format.Hence,thefilepointerwillbeattheendofthefileifitexistsanditispresentintheappendmode.Anewfilewillalsobecreatedifthefilementioneddoesnotexist.
a+ Itexecutestheopeningofafileandallowsappendingandreadingofthefile.Thefilepointerisattheendofthefileifthefileexists.Hence,thefilepointerwillbeattheendofthefileifitexistsanditispresentinappendandreadmode.Anewfilewillalsobecreatedifthefilementioneddoesnotexist.
ab+ Itexecutestheopeningofafileandallowsappendingandreadingofthefileinthebinaryformat.Thefilepointerisattheendofthefileifthefileexists.Hence,thefilepointerwillbeattheendofthefileifitexistsanditispresentinappendandreadmodeinbinaryformat.Anewfilewillalsobecreatedifthefilementioneddoesnotexist.
HowtousethefileObjectAttributesImmediatelyafilehasbeenopened,then,itbecomesafileobjectforwhichmuchotherinformationcanbederivedinpythonrelatingtotheinformationinthefile.
Thefollowingattributescanbeexecutedtothefileobject:
Attribute Description
file.closed ThisallowsPythontoreturnstruewhenthefileisclosed,otherwise,itisconsideredasfalse.
file.mode Thisreturnsthemodeofaccessforwhichthefilewasopened.
file.name ItreturnsthefilenameopenedinPython.file.softspace Thiswillreturnsfalsewhenspaceisrequired,
otherwise,itwillbetrue.
Anexampleoftheprogramtobeexecutedincludes
Example
Theoutputwillbeasseeninthisscreenshot:
Inmostcases,whenworkingwithareal/actualfilesuchasanexcelfile.Then,theimportfunctioncanbeusedinthiscase.AssumingyouhaveafilesavedasaCSVfilename“goodmen.csv”.Youcanopenitanduseitinmanyotherways.Moreover,youcanalsocheckoutthename,confirmedifthefileisclosedornot,confirmthemodeandsoftspaceflagasillustratedabove.Thefollowingprogramcanbeusedtoaccessit:
Useanyotherfilewithadiffnameandseewhathappenswiththefile.Justchangethenamegoodmen.csvwithyournewfilenameinthecsvformat.
Closingofafileusingtheclose()attributeinPythonThisallowsPythontocloseafileobjectandassumesanyinformationthathadnotbeenwrittenandclosesthefileobject.Thisensuresthattheprogramdoesnotexecuteanyotherfunctionafterthathadbeendone.
However,pythonisalsoabletocloseafileautomaticallywhenadifferentobjectisassignedtothefile.But,itisagoodpracticetoalwaysclosethefileusingtheclose()function.
Thisisimplementedusingthefollowingsyntax:
fileObject.close();
Forexample:
Thepreviousfileopenedwasf2.
Thefilecanthereforebeclosedusingtheattribute:
Theoutputafterrunningthisfilewillbeasshowninthescreenshotbelow:
Summary
ItisimportanttoknowthatbeforeyouareabletoreadafileinPython.Itmust
beopenedfirst,usingtheopenfunctionasdescribedinthischapter.
Next,youwillbeabletoexecuteandfindouttheattributesofthefileusingthevariousattributesasmode,filename,spaceandmanymoreattributes.
Finally,alwaysensurethattheprogramisclosedusingthefile_nameobject.close()functioninPython.Itallowsyoutorunanotherprogramandmakesthepythonprocessquickinitsexecutionofprogramseveninlimitedmemorycapacity.
Chapter11:ReadingandWritingFilesinPython
Inthelastchapter,welearnedhowtobeabletoopenandcloseafile.
AfilethatisopencanallowreadingandwritingdependingwiththemodeselectedforexecutioninPython.Usingthefileobjectsallowsonetoaccessmethodsthatwillenableonetomanipulatedatainvariousways.Thismakeslifeforpeopleeasier.Inthischaptertherefore,wewouldliketoknowhowwecanbeabletoreadfileusingtheread()andwrite()methodsforreadingandwritingfiles.
Usingwrite()MethodThisattributeallowsonetoaddanythingintheformastringtoanopenfile.NotethatPythonstringsneedtohavebinarydataandmaynotjustacceptanyformoftexttobeusedinthiscase.
Inaddition,usingthewrite()techniquemanynotintroduceanewlinecharacter('\n')attheendofthestring.
Thesyntaxforthewrite()canbeexpressedasbelow
Here,isanexampleofhowthiscanbeappliedintherealPythoncode:
Since,thisfiledoesnotexistinpython,itwillcreateanewfilecalled“goodmen.text”andthenitwillcloseafterexecutionofthefilenameobject.close().
Whenthefileisopened,itwillcontainthefollowingtextinit.OpenitinNotepad.
Howtousetheread()attributeinPythonThismethodallowsstringstobereadfromanopenfile.Thepythonstringsmaycontainbinarydatabesidestheuseofthedataintext.
ThesyntaxforreadingfilesisexpressedasfollowsinPython:
Inpython,thefileobjectistheassignednameinpythonatthetimethefileisbeingopened.Forinstance,goodmenfilesabovewereassignedanobjectvaluef2.
Inthiscase,thisallowsthefileopenedtobereadfromthestartofthefileandwhenthecountisabsent,then,itwillreadtheentiredocumenttotheendofthefile.Hence,itisimportanttospecifyhowmuchinformationmaybeneededwhentryingtogetspecificinformationinPython.
Note:YoudirectPythontodoeverythingthatyouwouldlikeittodo.
Forexample:Usingthepreviousfileinthischapter“goodmen.txt”
WecanreadtheabovefileinpythonandseewhatresultsitgeneratesinPython.
Theoutputwillbeexpressedasfollows:
GettingthepositionsoffilesThisisthemethodthatcanbeusedinfindingthepositionofatextwithinafile.Thisusesthetell()attributeinpython.ThisallowsPythontodothenextreadorwritefromthepositionindicatedfromthebeginningofthefilecreated.
However,wecanalsobeabletochangethecurrentfilepositionofafileusingtheseek(offset[,from])method.Theargumentoffset;suggeststhenumberofbytestobemovedwhiletheotherargument,fromshowsthespecificpositionwherethebyteswillbemovedfromthecurrentposition.
Whenthevaluefromissetaszero(0),Thissuggeststhatthefilehastobereadfromthebeginningofthefileasthemainreferencepointwhileavalueofone(1)isusedtorefertthecurrentposition.Avalueof2isappliedtoindicatetheendofthefileasthemainreferencepoint.
Usinganexamplebelow:Letustakeafilefoo.txt,whichwecreatedabove.
Theoutputwillbeasrepresentedinthescreenshotbelow:
HowtoRenameandDeleteFilesPythonalsoallowsonetobeabletoprocessfilesinthepythonos.Thisincludesprocessessuchasbeingabletorenamefileordeletefileswithouttheneedtomanuallydeletethefiles.Thiscanbestbeappliedfirstbytheuseoftheimportstatementandthenyouwillbeabletocallanyfunctionsthatcanbeperformed.
Usingtherename()syntaxTherename()attributeallowsonetousetwoarguments.First,youwillberequiredtousethecurrentfilenameandthenfollowedbythenewfilename.
Agoodexampleoftheapplicationisasshownbelow:Followingistheexampletorenameanexistingfiletest1.txt:
Deletingfilesusingtheremove()MethodThisisappliedwhenonehastodeleteafile.Thisrequiresthatyouwillhavetoprovideanameofthefilethathastobedeletedintheargument.
Themainsyntaxfortheprocessis:
Thefollowingisanexampleonhowtodeleteanexistingfilecreatedasgoodmen2.text.
WorkingwithDirectoriesinPythonAllfilesarecontainedwithinvariousdirectories,andPythonhasnoproblemhandlingthesetoo.TheOSmodulehasseveralmethodsthathelpyoucreate,remove,andchangedirectories.
Themkdir()MethodYoucanmakeadirectoryusingtheattributemkdir()methodinbuiltwiththeOSinPython.Thiswillbeabletocreateanewdirectoryinthecurrentdirectory.Thisisdonebyintroducinganargumentthatwillcontainanargumentwhichwillhavethenameofthedirectorythatneedstobecreated.Thesyntaxtobeusedis:os.mkdir("newdir")Thefollowingexamplecanbeusedforcreatinganewdirectory(new_programs)inthecurrentdirectory.
ChangingdirectoryMethodTochangethedirectory,usetheattributechdir()tochangethedetailsofthecurrentdirectory.Thisisanargumentthatmakesthenewcurrentdirectory.
Ithasthesyntaxasfollows:os.chdir("newdir")Asagoodexampleforthissyntax,let’schangetothecurrentnewdirectory"homeworking_programs".
HowtogetthecurrentworkingdirectoryThisisachievedbytheuseofthe
getcwd()attributeinpython.Itcanbeabletodisplaythecurrentdirectorythatisworking.Thesyntaxusedisexpressedas:os.getcwd()Aperfectworkingcodeforgettingtheworkingdirectoryisasshowninthisscreenshot
HowtodeleteadirectoryThisisthetechniquewhichonecanapplywhentheywanttoremoveadirectory.Theattributeinfunctionforthisprocessisthermdir()Thismethodenablesonetodeletecompletelythedirectory.ThisisinitiatedasanargumentinPython.However,notethatallthecontentsthathadbeenpreviouslysavedinthedirectorywillneedtoberemovedfirstbeforeitcanbedeleted.Thesyntaxfortheargumentissetas:os.rmdir('dirname')Toremove“tmp/new_programs”asadirectory.Thefullnameasitappearsinthedirectoryisprovided.Hence,itwillsearchforthenameinthecurrentdirectory.
ManipulationoffilesanddirectoriesTherearetwospecialmethodswhichallowonetobeabletohandleandmanipulatedifferentfilesanddirectories.Theseareapplicableinbothwindows,UnixOS.
Theyincludethefollowingmethods:
FileObjecttechniques:Thefileobjectallowsafunctiontochangefiles.OSObjecttechniques:enablestheprocessingofbothfilesanddirectories.
SummaryInthischapter,wehavejustlearnedthatwecanbeabletodeleteadirectory,createanewdirectory,changeadirectory,getadirectorynameandmanyotherfunctions.ThisisanimportantprocessinPython.Itmakeslifeeasier.YouwillbeabletocreateafileinPython,createanewdirectory,saveit
thereandevenconfirmifthefilehasbeensaved,andclosethefileasusual.
PracticeExercise
1. Anewfilenamed“1000_keywords.csv”hastobeopened,readasabinaryfile.WriteaPythoncodethatwillexecutethisprocess.
2. Thefilenamealsohastobechangedto“Smart_words.csv”writeaprogramthatwillexecutetheprocessandstoredinthesamedirectory.
3. Johnisworkingandisnotsureinwhichdirectoryhehasbeensavinghiswork.Writehimatwolineprogramthatwillbeabletoidentifythedirectoryhehasbeensavinghiswork.
4. Johnhastwolonglistsofstudentsthatheneedstomergethemtogether.HowcanhebeabletocreateasinglelistofnamesinPython?Howcanhealsobeabletosavethelistinhiscurrentdirectorynamed“students”?Toavoidconfusion,hewillberequiredtodeletetheotheroriginalfilesinthecurrentdirectoryandsavethesamefilesinadifferentdirectorynamed“Oldrecords”.Developasinglepythonthatwillbeabletoaccomplishthisprocess.
5. Mikeisatutorforaschool.Thefinalexamsweredoneandhehasfinishedmarking.However,hehastocalculatetheoverallmarksbyaddingthemeanofthecatmarksforcat1andcat2whichaccountfor30%andaddthemarkstothefinalexamsmarkwhichisoutof70%.Hehasonlyadaytogobeforethedeadline.HowcanhebeabletodothisautomaticallywithoutmuchhustleinPythonandaccomplishthetaskinlessthan10minutesfor60students?
Chapter12:ManagingDatabases
Theuseofdatabasesbacktobeforethe1970’s.SQLisoneofthefewdatabasesthathaveawideareaofapplicationandmoreespeciallywithrespecttopythonprogramming.SQLhasawell-structuredlanguagewithquerywhichisbasedoncreatingrelationshipsasamodelforsharinginlargedatabanks.
Infact,SQLisoftenpronouncedassequelwhenreaddirectlyinEnglish.Currently,itisnowoneofthebeststandardsintheAmericannationalstandardsInstitutes(ANSI)after1987.ThisisbecausemostofthepeoplepreferusingmSQL,postgressSQL,MySQLandotherformsofSQL.
Whatisadatabase?
Adatabaseisdefinedasacollectionoforganizeddata.Theorganizationofthedataallowsprocessingofthedataeitherbywayofdeletingfiles,rearranging,addingnewinformation,replacingcontentandmanyotherfunctions.
Adatabaseisalsothedataitselfthathasbeenstoredfordatabankforspecialreasons.Itcanalsobeassociatedwiththedatabasemanagementsystem.Thedatabasemanagementsystemisthesoftwarethatcanbeusedintheprocessingofthedatabytheuser.
Theuserofthedatabasemaynotberequiredtobehumanbutprogramsandapplicationstoo.
Pythonasintroducedatthebeginningofthisbookwasexpressedasaninteractivelanguage.PythonhastheabilitytointeractwithadatabasesuchasSQL.Itthereforehasthepotentialofinteractingasauserforthedatabase.
ItispossibletouseSQLiteandotherSQLformsfromPythonasaprogram.ItisastandardthatthedatabaseinterfaceforPythonisDB-API.ThisisusedbyPythoninterfaceswheninteractingwithPython.Whileitisacommoninterface,itcanalsobeusedinrelationaldatabasesusingcodesdevelopedinPythonforcommunicationwithdatabases.Thelanguageusedisthesameandregardlessofthetypeofthedatabasethatwillbeusedandthemodulethathastobeapplied.
Already,Ihaveaddressedafewexamplesofdatabases;SQLandMySQL.Here,weshalllookateachoneofthemindividually.
SQLite
Thisoperatesasimplerelationaldatabasesystem.IthastheabilitytosavethedatainthesimpledatabasesystemsinthesimpleregulardatafilesinsimplelocationsofacomputersuchasthecomputermemoryintheRAM.ItisverycompartiblewithsimpleapplicationssuchasMozillar-Firefox,SymbianOS,androidandmanyotherOSprograms.
Itisalsoveryfastsinceitusessimplefilesandhasthecapabilitytooperateforlargedatabases.
TheoperationoftheSQLitereliesonimportingofthemodulesqLite3.Then,aconnectionisrequiredwiththeobject.Theconnectionobjectwillrepresentthedatabase.Theargumentoftheconnectionisthenameofthedatabasesuchas“companys.db”.Itfunctionsbothasanameofthefile,wherethedatawillbestoredandasthenameofthedatabaseitself.Presenceofthefilenamewillhavetobeestablishedandifthenameexists,itwillbeopened.
Note:thedatabasehastobeanSQLite,ifthenameexists,thenithastobeopened.
Letuscreateadatabaseusingthefollowingcode.Thiswillbeabletoopenadatabasecompany.Thefileinthiscasemaynotneedtoexistinthiscase.
Usingthiscode,youwillbeabletocreateadatabasethatwillhavethename‘Company”.ThisisacommandthatinitiateandcreatesadatabasecompanyinanSQLserver.
Whenyoutrytousethecommand:
"sqlite3.connect('company.db')" again
Thiswillopenapreviousdatabasewithasimilarnamethathadbeencreated.
Whatyoudevelopedisanemptydatabaseandwhathastobedonenextistocreatetablesintheformatneededsoastobeabletoinsertandretrieveinformationinthewaythatisneeded.
AnSQLcodefordevelopingtable"staff"inthedatabase"company"lookslikethis:
ThisishowitcanbedoneinanSQLinthecommandshell.ThiscanbedoneinPythondirectly.AcommandcanalsobesenttoanSQLorSQLite.ThisisonlypossiblewiththeuseoftheSQLcursor.Therelevanceofacursoristoenableonetoaccess,read,writeanduseinformationinadatabase.ItcanalsobeusedIfetchingforinformationfromadatabasewithapreciseoutput.
InmostofthePythonprograms,itisusedforperformingmostofthecommands.
Thiscanbedonebycallingthecursormethodasawayofestablishingtheconnections.Anynumberofcursorscanbecreated.Theycanalsobeusedtogoovertherecordsandinformationwhicharetheresultsfromadatabase.
Therefore,acompletePythoncodefordevelopingapowercompanywouldlooklikethis:Rememberthestafftablewillalsobecreatedinthisdatabase:
Inthesyntaxabove,itisclearthattheAUTOINCREMENTparthasbeenremoved.NotethatinSQL,The“INTEGERPRIMARYKEY”alsoautomaticallyautoincreasethevaluesinthefieldrequiredinthetableinSQLite3.
Thiscanalsobeexpressedinthesensethatwhenacolumnofatableisdeclared
tobeanINTEGERPRIMARYKEY.EverytimewheneveraNULLisusedasaninputforthecolumn,TheNULLvaluewillbeautomaticallygetconvertedtoanintegerwithavaluelarger/higherthanthepreviousvaluebyoneinthecolumn.Whenthetableisempty,itwillautomaticallygiveavalueonefortheexistingnumber.Forinstance,whenalargestexistingvalueforacolumnis9234576898344,anynewvaluethatwillbeaddedwillbeonevaluehigherthanit,hencethevalueinSQLitewillbeanunusedvalueselectedrandomly.
Tothisfar,wehavebeenabletocreateadatabaseandatableinsideitwithseveralcolumns.Butcurrently,nodatahasbeencreatedonit.
Tocreatethedataonthetable,wewillhavetobeabletopopulatethetableusingasimplePythoncommand“INSERT”commandtoSQLite.Similarly,wewillneedtoexecutethecodeasamethodofpopulatingthetable.
UsethebelowworkingexampletoknowhowmakingadatabasecanbeeasyandinterestingusingSQLiteandPythonasthebestinteractivelanguage.
Trytheprogrambelow:
Toruntheprogramyouwilleitherhavetoremovethefilecompany.dboruncommentthe"DROPTABLE"lineintheSQLcommand:
Tobeabletoinsertthedataonadatabaseinpython,youwillnotbeabletoliteraryinsertthedataintoatable.Butwillberequiredtohaveamanydataintheformsofdatatypesdiscussedinthebeginningofthisbook.Itcanbeintheformofdictionariesoralistwhichcanbeusedastheinputoftheinsertstatement.
ForExample,usingalistofpersons,itispossibletoinsertthenamesinanexistingdatabasecompany.dbandatablestaff.ThiscanbeachievedusingtheINSERTstatementinPython.
ItispossiblequerythestafftableinPython.FollowthefollowingcodetoknowhowthiscanbeachievedveryeasilyinPython.Thisenablesyoutobeabletoretrieveanyinformationfromthedatabaseandaswellconfirmandverifytheinformationstoredinthedatabase.
First,savethisprogramas“query_SQL-company.py”andthenrunthisprogram.Thiswillgiveyouthefollowingproductswegetthefollowingresult,dependingontheactualdata:
MySQL
InordertouseMySQLdb,itthemodulehastobeinstalledonacomputeronwhichyouwillbeworkingon.However,onotherprogramssuchasUbuntuandDebian,itisveryeasy.
JusttypethefollowingcodeinPythonandwaitforittobeinstalled:
NotethatbesidestheimportandtheconnectsfunctionsmethodandeverythingelseasappliedinSQLite.TheworkingofMySQLdboperateslikethis:
First,youhavetoimportMySQLdbmodulinPythonTocreateaconnection,openaconnectiontotheSQLserverUseboththesendingandreceivingcommandsAlwaysclosetheconnectioninSQL
TheimportandconnectionfunctionsinMySQLdbwilllooklikethecodesshown:
PracticeExercise
CreateadatabaseusingSQLite3andnameit“students.db”.Inthedatabase,createatableinthedatabasecalledstd8_studentsandprovidetheinsertandcommitfunctions.Writeacodethatwillbeabletoretrieveinformationfromthesamedatabaseandprovidealistofthenamesofstudents,gender,ageandcodeforthestudents.
Conclusion
Imostsincerelythankyoufordownloadingthisbook!
ItismybeliefthatthisbookwasabletohelpyoulearnhowtointeractwithpythonandteachyouhowtousenumbersandtextsinvariouswaysinPython.
Thenextstepisforyoutoensurethatyoupracticehowtousethisbookandinformationgiventoyouonadailybasistoperfectonhowtousenumbersandtextsinpython.Notethatpythonitselfisveryinteractivewillrequireverycloseattention.
Finally,ifyoubelievethatthisbookhashelpedyoulearnaPython.Pleasetaketimetoshareyourthoughtsonhowthiscanbeimprovedtomakethebookevenbetterforothers
Also,IencourageyoutoshareyourreviewsthroughAmazon.Thiswillbegreatlyappreciated!
Thankyouagainforreadingthisbook.
IhopethatyouenjoyinteractingwithPython.
BonusFreePythonProgrammingVideos
Whenyousubscribeviaemail,youwillgetfreeaccesstoatoolboxofexclusivesubscriber-onlyresources.Allyouhavetodoisenteryouremailaddresstotherighttogetinstantaccess.
Togetinstantaccesstotheseincredibletoolsandresources,clickthelinkbelow:
=>Clickhereforthebonuscontent<=
Top Related