aflexsystem. python: python programming guide - learn python in 24 hours or less (programming

95

Upload: others

Post on 11-Sep-2021

62 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming
Page 2: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

PYTHONMADESIMPLE

Page 3: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 4: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

BonusFreePythonProgrammingVideos

Whenyousubscribeviaemail,youwillgetfreeaccesstoatoolboxofexclusivesubscriber-onlyresources.Allyouhavetodoisenteryouremailaddresstotherighttogetinstantaccess.

Togetinstantaccesstotheseincredibletoolsandresources,clickthelinkbelow:=>Clickhereforthebonuscontent<=

Page 5: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

TableofContents

IntroductionChapter1:SettingUpPythononYourcomputerChapter2:InteractingwithPythonChapter3:Boolean’sinPythonChapter4:Boolean’sandConditionalexpressionsChapter5:Useofif–elifstatementsinmakingMultipleTestsinPythonChapter6:UseofNestedControlflowstatementsinPythonChapter7:CompoundBooleanExpressionsinPythonChapter8:PythonDataVariables(Numbers,Lists,Tuples,StringsandDictionaries)Chapter9:BasicOperatorsinPythonforCalculationsChapter10:OpeningandClosingFilesChapter11:ReadingandWritingFilesinPythonChapter12:ManagingDatabasesConclusionBonusFreePythonProgrammingVideos

Page 6: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 7: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 8: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 9: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 10: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 11: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 12: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 13: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Warning

Mostofthetime,installingPythoninWindowsmayfaceafewchallenges.Itmayfailtogetconfiguredtotherightpath.ThiscanbesolvedbytypingthefollowingtextinthepythonPowerShell

Then,eitherRestartthePowerShellorthewholecomputersoasitgetsfixed.

Windows:WhatYouShouldSeeJustbyopeningPythonThisiswhatyoushouldsee

Tofindhelp,Typehelp()followedbyenter.Thisiswhatyouwillsee!

ForthepreviousversionsofPython;thisiswhatyouwillseeastheoutput:

Page 14: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 15: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 16: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

AsamplescreenshotofthissearchonGoogleisattachedbelow:

Page 17: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 18: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 19: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

MixingtheindentationsinmostcasesbringanerrorinthepythonshellwhentheprogramisrunbypressingonF5keyorbyselectingrunfollowedbyrunmodule,eitherway,itisthesame.

MultiplelinesinpythoncanalsobeusedMostofthestatementsinpythonendupwithanewline.However,linecontinuationcanbeusedbytheuseofcharacters(\).Thisshowsthatthelineisacontinuationfromthepreviousstatement.

Forexample

However,whenthestatementsarecontainedwithin[],(),or{}typesofbrackets.Theydonotneedtheuseofthelinecontinuationcharacters.

Forexamples

Page 20: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 21: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Notealso,thatacommentcanbeplacedinthefollowingways:

1. Itmaycomeafteralineofcode2. Youcanalsocommentafterasintheshownbelow.3. Commentscanalsobeinmultiplelines,buteverylineneedsto

startwithahash(#)sign.

BlankLines

Blanklinesinpythonareignoredautomatically.Theycouldbeablanklinewithonlywhitespace.Theycanalsobeblanklinewithacommentusingahash(#)sign.Theyareallignoredbypython.

However,whendevelopinganinteractiveinterpreter.Ablanklinecanbeusedtoterminateamultilinestatement.

UsingmultiplestatementsonasinglelineTocreatemultiplestatementsonasingleline,asemicolonisused.However,thisisonconditionthatthenewstatementdoesnotrepresentanewblockofcodethatcaninitiateadifferentprocess.

Thesemicolonscanbeusedasfollows:

Page 22: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

MultipleStatementGroupsasSuites:

WhentherearegroupsofasinglecodeexpressedassinglestatementsinPython,theyarereferredtoassuites.

Compoundstatementsinvolvingtheuseofwordssuchasif,def,while,class;requireaheaderlineandasuite.

Moreover,alsoimportantaretheheaderlines.Theystartastatementwithakeywordandtheyterminatewithacolon(:).Theyrequireafewotherlinessoastheycanmakeupasuite.

Hereisanexampleoftheuseofif,elifandelsetomakeasuite.

Note:theindentationasusedisimportant.

Insummary

InteractingwithpythonrequiresthatyoushouldbeabletocomprehendthebasicrulesforusingPython.Afullfunctionalcodewillrequirethattherightindentations,blanklines,colons,commentsandotherinteractingapproachesarecorrectlyapplied.

Page 23: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 24: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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:

Page 25: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 26: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

JustlikeIhaveexpressedinthepreviousexample,thiscodescanbereadlikeanEnglishstory.Otherwordssuchasotherwisecanbeusedinsteadofthewordelse,however,weuseshorterwordsinPythontoreducethebulkofwordinginprogramming.

Notealso,thatthecodehastwoindentedblocksofcode.Theaftertheifandaftertheelse.Thefirstblockistheifstatement.Theindentationisexecutedonlyoftheifistrueotherwise,nothinghappens.Next,whenitisfalse,theelseisexecutedaswell.Hence,whenusingtheif..elsestatement,onlyoneoftheheadingscanbeexecutedatanyone,whenifistrue,elseindentedblockisnotexecuted,butwhenifisfalse,thentheelseindentedblockisexecuted.

Page 27: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 28: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 29: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

arethenpaiddoublethenormalrate.Thiscanallowustomakeapythoncodethatwillbeabletodothecalculationforthemoneythatispayableperemployee.

Thesetupforthefunctioncanbeexpressedasfollows:

Trytoreadthesetupforthefunctionasexpressedbelow:

Thiscodewillbeabletohandletwocases,whenlessthan40hoursoftotaltimeisworkedandwhenmorethan40hoursoftotalhoursworkediscovered.

Whenmorethan40hoursoftotalworktimeiscovered,then,anewvariablewillhavetobeintroducedcalledovertimeHours.Thiswillbeabletomanagetheamountoftimeworkedinexcessofthe40hourstotalworktimeandincludedinthetotalwageforthemonth.

Sincewearetrainingyouasaprogrammer.TrytoseehowthissolutioncanbereadinEnglish.

Then,trytorunthisprogramoutandseetheresults:

Usethisprogramsnamedwages.pyasanexampleofaprogramforthisexercise.

Thisprogramhasadoptedtheuseoffloatingstingspointformat.(StringFormatsforFloatPrecision)soastoallowtheuseofthecentsintheanswertotwodecimalplaces:

Page 30: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Inmostcases,thiswillbeabletomanagethenumericvaluesbutthiscanaccommodatethedecimalconversionsfromstringsviafloatsandnotintegers.

Alternatively,adifferentversionoftheexpressioncodeforthebodyofcalculatingweeklywagescanbeusedinthecodeusedabove.

Thisisjustageneralformulawhichwillbeabletomanagetheexpressionintheformulaandallowtheparameterstoaccommodatetheifstatement.Thesameproblemcanbesolvedusingmanyotherwaysinwaythatwillstillprovideyouwiththesameoutput.

Page 31: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 32: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 33: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Thesyntaxappliedinthisuseofif,elif–elseclauseisillustratedbelow.Thishelpsyou

Notethatalluseofif,elif,andthefinalelseareallalignedononeline.Thenumberofeliftobeusedisnotlimitedwitheveryofthelinefollowedbyanindentedblock.

Whathappensisthatoneoftheindentedblockwillbetheonetobeexecuted,whenitistheonethatcorrespondstothefirsttrueconditionssetusingtheifstatement.Otherwise,whenalltheconditionarefalse,thefinalelsewillbeexecuted.

TheuseofifandelifisanimportantformsofpythonContraction.Careneedbeobservedwhenusingthecontractedformofpythoncodes.Itissupposedtowrittenaselifandnotelseif.Thegradingmarks.pyisagoodexampleoftheuseofthiscodeillustratedabove.

Page 34: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Alternativesyntax

Theotherwayinwhichtheifstatementcanbeappliedisbytheuseoftheif-elif-andremovingtheelsestatementinthecode.Thissuggeststhatthesyntaxif-elif-elseismodifiedsothatthefinalblockofcodewithelseisremovedoromitted.Thisisthesameasthenormalifstatementthatdoesnotincludeanelseinitscode.Thisallowsforthenoblockofcodetobeexecutedandonlyoccurswhennoneoftheconditionsinthetestsistrue.However,whenanelsecodeisincluded,oneoftheindentedcodehastobeexecuted.Intheabsenceoftheelsecode;atmostoneofthecodeastobeexecuted.

Thiscodewillonlybeabletoprintalinewhenevertherewillbeaproblemwiththesuitcase.

Hereisanexampleofthecode:

Page 35: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 36: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Chapter6:UseofNestedControlflowstatementsinPython

BynowIbelieveyouarebecomingconversantwiththeabilitiesandpotentialofPythonlanguage.Itcanbeappliedinavarietyofwaysassimplestatementsandaswellascomplexorcombinedstatements.Onesuchexampleiswelldemonstratedintheuseoffor-ifandelsestatements.

Inthiscasenow,notethatforandifstatementscanbenestedinsideeachotherinanindentedblockofcode.Forinstance,fromaseriesofvalues,onecanbeabletoonlyselectpositivevaluesfromamixofnumericalinanarbitrarylistofnumbers.

Forexample.Usingthefollowingcode,itiseasiertoselectonlypositivevaluesfromamixofnumbers:

Justforamoment,trytoreadtheprogrambyfollowingthecommentsprovidedinthecode.Usingahumaneye,youwillbeabletoselectthenumberscarefully,butusingacomputer,thiswillbemadesystematicallycheckingeverynumberconsistently.Usingtheifstatement,everynumbercanbecheckeddeterminewhetheritcanbeprinted.

Thiscanbeobservedbelow:

NestingofthestatementsasintheuseofIfexpandsthepossibilitiesof

Page 37: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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:

Page 38: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 39: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Themiddleifshouldnotbechangedtomakeitanelifasusedinmanyothercases.Thisisbecausethereisapossibilitythataballcanreachacornerandtherefore,itmayrequirethatbothdxanddyshouldbechanged.

Avarietyofaccessmethodsforgraphicsarepresentthatcanbeusedusingdifferentshapessuchascircleswhichcanbedefinedbydescribingthecentrepoint.

TheycanbeaccessedbyusinggetCenter()method.Thiswillbeabletogenerateacloneofthepointswhichcanbereturned.EverycoordinatecanberetrievedbyusinggetX()andgetY()criteria.

ThismaybeanewfeaturethatcanbeappliedinthedefinitionofthecentralfunctionofabouncingballooninaboxbounceInBox.

Thisanimationwillbeabletodeveloparepeatloopwhichcanbeaccomplishedthroughaseriesof600steps.

Thiscanbecapturedinthisexperiment.

Thiswillmoveaballoonwhilebouncingfromanypointwithinarectangle.This

Page 40: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

iswhatisexpressedinthefunctionofthecode:getRandomPoint.Thisfunctionallowstheuseofrandrangefunctionderivedfromthemainmodulerandom.

Parameterswithfunctionsrangeandrandrangeexpressestheendwhichhasbeendefinedinthepastandwhichisthelastvaluethatisactuallydesired.

Thefullprogramthatwillallowonetoanimateacompleteprogramthatwillbeabletoshowarepeatingbouncingballoon/ballisasexpressedbelow.Notethatthereistheuseofthefunction,bounceInBoxandgetRandomPointtoastheprogramtobecomplete.

Thesearealsonottheonlyfunctionsthatcanbedone.Noteverythinghasbeendescribedasdemonstratedinthecodebelow:manyotherthingswillneedmoreresearchtounderstandhowtheyfunction.But,theycanbeusedtogethersothataprogramwillbeabletofunctionappropriately.Thisprogramwillbeabletoshowaballbouncingoffthesidesofthewindow.

Page 41: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming
Page 42: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 43: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 44: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Chapter7:CompoundBooleanExpressionsinPython

Perhaps,thiscanbebestexpressedusingvalidexamples.Letusconsiderthiscasebelow:

ForonetobeeligibleforgraduationfromauniversityinUS,itwassetthatstudentsneeded120creditsandatotalGPAofminimum2.0.

UsingPython,createaprogramthatcanbeusedtoselectstudentsthatwouldbegraduand’sfortheyear.

Thissuggeststhatthiscanonlybetruewhencreditswillbeequaltoorgreaterthan120.

WhileGPAwasalsogreaterorequalsto2.0.

Agoodprogramwilllooklikethis:

Applicationofcompoundexpressions

Thiswillshowthatacompoundconditionwillbetrueifbothoftheconditionsaretrue.However,itwillbeseenasfalsewhenatleastoneoftheconditionsisfalse.

Exercise

Previously,wehaddiscussedtheuseofifandelifstatementsincaseswherebothtestswheretheywillappearinthesameblockwhentheconditiontobeappliedwastrue.

Page 45: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 46: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 47: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Summary

Itisnotarequirementthatyouneedanif-elsestatementsothatyoucanbeabletochoosebetweenTrueorFalsevalues.ThiscanbeuseddirectlyusingtheBooleanexpressionsasdescribedbefore.

Similarly,otherexpressionswhenusingthecompoundexpressionsasinthiscase:

end1<=val<=end2

Themaincharactersareend1andend2.Thisissimplyastandardmathematicalsyntaxwhichcanbeusedinchainingcomparisons.Thenumbersofcomparisonscanbechainedusingtheseexpressionsusingapproximatenotations.NotealsothatthiscanonlybesuccessfullycodedinPythonunlikeotherprogramslikeJava,andC++.

Theycanalsobetranslatedinwaysthatcanbereadinmanyothercommonlanguagesasshownbytheexpressionbelow:

end1<=val

val<=end2

Ontheotherhand,anauxiliaryfunctionisBetweencanalsobeused.ThisisanisInsidefunction.TheisBetweenfunctioncanbeusedtofindthevaluesofthexcoordinates;andalsotocheckforthevaluesofthewhycoordinatesaswell.

Page 48: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 49: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

makeColoredRect.ThisisagoodexampleforuseofgraphicaltoolsinPython.

Thecodethathasbeendevelopedisquitelongandisenshrinedwiththegraphicalcodesfordrawingpicturesandbuttonsandhassectionswithqueriesforaskingtheusetoselectthecolorsforapicture.Youwillalsoobservethecodeshaveanif-elif-elsetesttocheckonwhichbuttonshavebeenpressedandsetthecolourofthepictureelementascommandedbytheprogram.

Page 50: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

TheonlynewaspectwiththisprogramwillbetheuseofthelongstatementsisInsideasshownbelow:

Pythonisaninteractiveprogramthatwillbeabletoreadthestatementsastheycontinuetothenextlineevenwhenthereisanunmatchedpairofbracketsandparenthesis.Itisrecommendedthatwhenyouhavealonglinethatwillbeable

Page 51: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

torunoverthescreenorpaper.Thisshouldbecontinuedtothenextline.

Tomakeafinalcharacteronalinewithabackslash(\)willbeusefulsinceitsuggeststhatthelinecontinuestothenextline.Thisisthebestwayofmakingyourworkneatsothatalmostallthestatementswillbeabletofitintothesameline.

Inaddition,thiswillalsobethebestwayofmakingyourcodessimple.UnlikePython,manyotherprogramswillrequireaspecialwayofterminatingalinesuchas‘;’whichservesascommandfortheprogramnottopayattentiontothenewlinescreated.InsomecasesinPython,anextraparenthesiscanalsobeusedanditwilldonoharmtotheprogramasshownintheaboveexampleusingtheisBetween.

Page 52: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

PracticalExerciseYouareeligibletovieforaUSsenatorandUSRepresentativepositionwhenyouareatleast30and25yearsoldrespectively.Inaddition,youmusthavebeenaUSCitizenforatleast9and7yearsrespectivelyforthesepositions.

Writeaprogramandcallitcongress.pytoobtaintheageandlengthofcitizenshipfromtheusertocontestforthetwopositions.

Enhanceyourprogramsothatyoucanbeabletoobtaintheage,lengthofcitizenshipandprintoneofthestatementslistedbelow

1. YouareeligibleforbothsenateandrepresentativeandSenate.2. Youeligibleonlysenate3. Youareineligiblerepresentative.

Page 53: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Chapter8:PythonDataVariables(Numbers,Lists,Tuples,StringsandDictionaries)

Variablesarereservedmemorylocationsinpythonwherevaluescanbestored.InPython,youareallowedtocreateavariablewhichyoucanreserveinthememory.

Inthebasisofthetypeofdatainputonpython,theinterpreterwillbeabletoprovidememoryandmakeadecisiononwhetheritcanbestoredonthememoryreservedfortheoperation.Hence,whenyouassignadifferentdatatypetospecificvariablesasyoudecide,youwillbeabletokeeptheintegers,decimalsandorcharactersinthisvariable.

Howdoyouassignavaluetoavariable?

Anequalsignisusedasanoperandforassigningvariabletoaname.TheoperanttotheleftoftheequalsignisreferredtoasthenameofthevariablewhiletheoperandtotherighthandsideisthevalueofthevariabletobestoredinPython.

Nameofvariable=Valueofthevariable

Thiscanbeshowninthefigurebelow:

Whenthiscodeissavedandrun.Thefollowingresultsareshownintheoutput.

Page 54: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 55: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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:

Page 56: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 57: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Outputsoftheabovecodeintheorderoftheprintcommandareasfollows:

Forhelpontuples,justtype[help(‘tuple’)orhelp(“tuple”)followedbyenter]inpythonshell.ThiswillprovidealistofallformsofclassesthatcanbeappliedonlistsPythonDictionary

Thesearehashtabletypesvalues.TheyareassociativearraysorahashwhicharesimilarlyfoundinPerlandconsistsofkeyvaluepairs.

Examplesofpairsincludethefollowingvalues:

Theoutputisexpectedtolooklikethiswhenthisprogramisrun:

Datavariablesapplyinalldatacodesdevelopmentandunderstandinghowtheyworkandoperateisveryessentialinlearningprogram.

Page 58: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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:

Page 59: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

However,whenamethoditems()isusedinadictionary,wemaynotbeabletogetalistback.But,wecanbeabletousetheitemviews,theitemviewswillbeconvertedtoalistwhenusedwithalistfunction.Noinformationwillbelostbyconvertingadictionaryintoalist.

Itisalsopossibletoreturntotheoriginaldictionaryfromtheitems(),evenwhenformedasalistoftuples,theyhavethesameentropy.However,theeffectivenessofthesameapproachesissimilar.

Therefore,dictionaryalsoservesasanefficientmethodtoaccess,replace,changeandvaryelementsofthedictionary.However,inlists,thesehavetobecodedbyaprogrammer.

TurnListsintoDictionaries

ThelistscanalsobeturnedintoPython;iftheselistssatisfycertainconditions.Letusconsidertwolistscontainingdishesandothercountries:

Page 60: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Adictionarycanbecreatedthatwillbeabletoassignadishtoacountry.Thiscanbedoneusingafunctionzip().Thiswillbeabletojointhelistslikeazip.Thiswillbeabletoiterateoveralist.Thissuggeststhatwehavetowrapalist()functiononthezipsoastocalltogetalist:

Thecountryspecificlistsofdishesarenowcompletelyconvertedtoalist.Thisisalistoftwotupleswhichhaskeysandvalueswhichcanalsobeautomaticallybeconvertibletoadictionarybyusingthefunctiondict().

Theonlymysterywillbetounderstandtheuseofthefunctionzip()whenonelistislongthattheother.

Thisisnotcomplicatedeither.Theprogramwillbeabletoignoreanyextraliststhatmaynotbepairedinanyway.

Here,Switzerlandwillnotbepairedinthiscaseandwillbeignoredintheoutputaspresented.

Allinone

Normally,werecommendnotimplementingtoomanystepsinoneprogramming

Page 61: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

expression,thoughitlooksmoreimpressiveandthecodeismorecompact.Using"talking"variablenamesinintermediatestepscanenhancelegibility.Thoughitmightbealluringtocreateourpreviousdictionaryjustinonego:

Thiscanalsobewritteninthisotherway:

Summary

Thedatavariablescomeinthefiveways:Theycanbeinformofnumbers,lists,tuples,stringsandfinallydictionaries.Eachofthemisveryuniqueandworkingwithpythonateverysingleprocessrequiresabasicunderstandingoftheirfunctionsandclasses.

Inpython,tobetterunderstandhowthiscanbeapplied.Youcanseekhelpfromthepythonbytypinghelp(‘object’)orhelp(“object”)followedbyenter.Thiswillprovideyouwithasolutiononhowanyofthevariablescanbeapplied.

Page 62: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 63: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 64: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

!=> 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

Page 65: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 66: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 67: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

- 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

Page 68: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

notorand Creatinglogicaloperators

Page 69: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 70: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 71: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 72: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 73: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Anexampleoftheprogramtobeexecutedincludes

Example

Theoutputwillbeasseeninthisscreenshot:

Inmostcases,whenworkingwithareal/actualfilesuchasanexcelfile.Then,theimportfunctioncanbeusedinthiscase.AssumingyouhaveafilesavedasaCSVfilename“goodmen.csv”.Youcanopenitanduseitinmanyotherways.Moreover,youcanalsocheckoutthename,confirmedifthefileisclosedornot,confirmthemodeandsoftspaceflagasillustratedabove.Thefollowingprogramcanbeusedtoaccessit:

Useanyotherfilewithadiffnameandseewhathappenswiththefile.Justchangethenamegoodmen.csvwithyournewfilenameinthecsvformat.

Page 74: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Closingofafileusingtheclose()attributeinPythonThisallowsPythontocloseafileobjectandassumesanyinformationthathadnotbeenwrittenandclosesthefileobject.Thisensuresthattheprogramdoesnotexecuteanyotherfunctionafterthathadbeendone.

However,pythonisalsoabletocloseafileautomaticallywhenadifferentobjectisassignedtothefile.But,itisagoodpracticetoalwaysclosethefileusingtheclose()function.

Thisisimplementedusingthefollowingsyntax:

fileObject.close();

Forexample:

Thepreviousfileopenedwasf2.

Thefilecanthereforebeclosedusingtheattribute:

Theoutputafterrunningthisfilewillbeasshowninthescreenshotbelow:

Summary

ItisimportanttoknowthatbeforeyouareabletoreadafileinPython.Itmust

Page 75: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

beopenedfirst,usingtheopenfunctionasdescribedinthischapter.

Next,youwillbeabletoexecuteandfindouttheattributesofthefileusingthevariousattributesasmode,filename,spaceandmanymoreattributes.

Finally,alwaysensurethattheprogramisclosedusingthefile_nameobject.close()functioninPython.Itallowsyoutorunanotherprogramandmakesthepythonprocessquickinitsexecutionofprogramseveninlimitedmemorycapacity.

Page 76: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 77: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Howtousetheread()attributeinPythonThismethodallowsstringstobereadfromanopenfile.Thepythonstringsmaycontainbinarydatabesidestheuseofthedataintext.

ThesyntaxforreadingfilesisexpressedasfollowsinPython:

Inpython,thefileobjectistheassignednameinpythonatthetimethefileisbeingopened.Forinstance,goodmenfilesabovewereassignedanobjectvaluef2.

Inthiscase,thisallowsthefileopenedtobereadfromthestartofthefileandwhenthecountisabsent,then,itwillreadtheentiredocumenttotheendofthefile.Hence,itisimportanttospecifyhowmuchinformationmaybeneededwhentryingtogetspecificinformationinPython.

Note:YoudirectPythontodoeverythingthatyouwouldlikeittodo.

Forexample:Usingthepreviousfileinthischapter“goodmen.txt”

WecanreadtheabovefileinpythonandseewhatresultsitgeneratesinPython.

Theoutputwillbeexpressedasfollows:

Page 78: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

GettingthepositionsoffilesThisisthemethodthatcanbeusedinfindingthepositionofatextwithinafile.Thisusesthetell()attributeinpython.ThisallowsPythontodothenextreadorwritefromthepositionindicatedfromthebeginningofthefilecreated.

However,wecanalsobeabletochangethecurrentfilepositionofafileusingtheseek(offset[,from])method.Theargumentoffset;suggeststhenumberofbytestobemovedwhiletheotherargument,fromshowsthespecificpositionwherethebyteswillbemovedfromthecurrentposition.

Whenthevaluefromissetaszero(0),Thissuggeststhatthefilehastobereadfromthebeginningofthefileasthemainreferencepointwhileavalueofone(1)isusedtorefertthecurrentposition.Avalueof2isappliedtoindicatetheendofthefileasthemainreferencepoint.

Usinganexamplebelow:Letustakeafilefoo.txt,whichwecreatedabove.

Theoutputwillbeasrepresentedinthescreenshotbelow:

Page 79: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

HowtoRenameandDeleteFilesPythonalsoallowsonetobeabletoprocessfilesinthepythonos.Thisincludesprocessessuchasbeingabletorenamefileordeletefileswithouttheneedtomanuallydeletethefiles.Thiscanbestbeappliedfirstbytheuseoftheimportstatementandthenyouwillbeabletocallanyfunctionsthatcanbeperformed.

Usingtherename()syntaxTherename()attributeallowsonetousetwoarguments.First,youwillberequiredtousethecurrentfilenameandthenfollowedbythenewfilename.

Agoodexampleoftheapplicationisasshownbelow:Followingistheexampletorenameanexistingfiletest1.txt:

Deletingfilesusingtheremove()MethodThisisappliedwhenonehastodeleteafile.Thisrequiresthatyouwillhavetoprovideanameofthefilethathastobedeletedintheargument.

Themainsyntaxfortheprocessis:

Thefollowingisanexampleonhowtodeleteanexistingfilecreatedasgoodmen2.text.

Page 80: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 81: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 82: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

thereandevenconfirmifthefilehasbeensaved,andclosethefileasusual.

Page 83: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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?

Page 84: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 85: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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.

Page 86: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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

Page 87: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

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:

Page 88: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Tobeabletoinsertthedataonadatabaseinpython,youwillnotbeabletoliteraryinsertthedataintoatable.Butwillberequiredtohaveamanydataintheformsofdatatypesdiscussedinthebeginningofthisbook.Itcanbeintheformofdictionariesoralistwhichcanbeusedastheinputoftheinsertstatement.

ForExample,usingalistofpersons,itispossibletoinsertthenamesinanexistingdatabasecompany.dbandatablestaff.ThiscanbeachievedusingtheINSERTstatementinPython.

Page 89: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

ItispossiblequerythestafftableinPython.FollowthefollowingcodetoknowhowthiscanbeachievedveryeasilyinPython.Thisenablesyoutobeabletoretrieveanyinformationfromthedatabaseandaswellconfirmandverifytheinformationstoredinthedatabase.

First,savethisprogramas“query_SQL-company.py”andthenrunthisprogram.Thiswillgiveyouthefollowingproductswegetthefollowingresult,dependingontheactualdata:

Page 90: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

MySQL

InordertouseMySQLdb,itthemodulehastobeinstalledonacomputeronwhichyouwillbeworkingon.However,onotherprogramssuchasUbuntuandDebian,itisveryeasy.

JusttypethefollowingcodeinPythonandwaitforittobeinstalled:

NotethatbesidestheimportandtheconnectsfunctionsmethodandeverythingelseasappliedinSQLite.TheworkingofMySQLdboperateslikethis:

First,youhavetoimportMySQLdbmodulinPythonTocreateaconnection,openaconnectiontotheSQLserverUseboththesendingandreceivingcommandsAlwaysclosetheconnectioninSQL

TheimportandconnectionfunctionsinMySQLdbwilllooklikethecodesshown:

Page 91: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming
Page 92: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

PracticeExercise

CreateadatabaseusingSQLite3andnameit“students.db”.Inthedatabase,createatableinthedatabasecalledstd8_studentsandprovidetheinsertandcommitfunctions.Writeacodethatwillbeabletoretrieveinformationfromthesamedatabaseandprovidealistofthenamesofstudents,gender,ageandcodeforthestudents.

Page 93: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Conclusion

Imostsincerelythankyoufordownloadingthisbook!

ItismybeliefthatthisbookwasabletohelpyoulearnhowtointeractwithpythonandteachyouhowtousenumbersandtextsinvariouswaysinPython.

Thenextstepisforyoutoensurethatyoupracticehowtousethisbookandinformationgiventoyouonadailybasistoperfectonhowtousenumbersandtextsinpython.Notethatpythonitselfisveryinteractivewillrequireverycloseattention.

Finally,ifyoubelievethatthisbookhashelpedyoulearnaPython.Pleasetaketimetoshareyourthoughtsonhowthiscanbeimprovedtomakethebookevenbetterforothers

Also,IencourageyoutoshareyourreviewsthroughAmazon.Thiswillbegreatlyappreciated!

Page 94: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

Thankyouagainforreadingthisbook.

IhopethatyouenjoyinteractingwithPython.

Page 95: AFlexSystem. Python: Python Programming Guide - Learn Python In 24 hours or less (programming

BonusFreePythonProgrammingVideos

Whenyousubscribeviaemail,youwillgetfreeaccesstoatoolboxofexclusivesubscriber-onlyresources.Allyouhavetodoisenteryouremailaddresstotherighttogetinstantaccess.

Togetinstantaccesstotheseincredibletoolsandresources,clickthelinkbelow:

=>Clickhereforthebonuscontent<=