+ All Categories
Home > Education > Python Programming A Comprehensive Beginner's Guide to Learn and Understand Python Language - By...

Python Programming A Comprehensive Beginner's Guide to Learn and Understand Python Language - By...

Date post: 12-Apr-2017
Category:
Upload: ali-dz
View: 64 times
Download: 3 times
Share this document with a friend
52
Transcript

PythonProgramming:

AComprehensiveBeginner’sGuidetoLearnandUnderstandPythonLanguage

TableofContentsIntroduction

Chapterone:Python…ASnakeorAProgram

Chaptertwo:InstallingPythontoYourComputer

Chapterthree:WhyPythonShouldbeLearned

Chapterfour:HowtoUsePythoninDifferentWays

Chapterfive:DesigningaWebsitewithPython

Chaptersix:TheManyVersionsofPython

Chapterseven:PythonandJava…WhataretheDifferences

Chaptereight:SeriesSetup

Chapternine:DetailandDatainput…HowDoYouAcceptThem?

Chapterten:IfReports

Chaptereleven:ErrorsandExceptions

Chaptertwelve:TipsandTricksforPython

Chapterthirteen:VariablesforPython

Chapterfourteen:OperatorsforMathinPython

Conclusion

FREEBONUS!

Copyright2016byJoshuaWelsh-Allrightsreserved.ThefollowingeBookisreproducedbelowwiththegoalofprovidinganinformationthatisasaccurateandreliableaspossible.Regardless,purchasingthiseBookcanbeseenasconsenttothefactthatboththepublisherandtheauthorofthisbookareinnowayexpertsonthetopicsdiscussedwithinandthatanyrecommendationsorsuggestionsthataremadehereinareforentertainmentpurposesonly.Professionalsshouldbeconsultedasneededpriortoundertakinganyoftheactionendorsedherein.ThisdeclarationisdeemedfairandvalidbyboththeAmericanBarAssociationandtheCommitteeofPublishersAssociationandislegallybindingthroughdatedtheUnitedStates.Furthermore,thetransmission,duplicationorreproductionofanyofthefollowingworkincludingspecificinformationwillbeconsideredanillegalactirrespectiveofifitisdoneelectronicallyorinthestamp.ThisextendstocreatingasecondaryortertiarycopyoftheworkorarecordedcopyandisonlyallowedwithexpresswrittenconsentfromthePublisher.Alladditionalrightreserved.Theinformationinthefollowingpagesisbroadlyconsideredtobeatruthfulandaccurateaccountoffacts,andassuchanyinattention,useormisuseoftheinformationinquestionbythereaderwillrenderanyresultingactionssolelyundertheirpurview.Therearenoscenariosinwhichthepublisherortheoriginalauthorofthisworkcanbeinanyfashiondeemedliableforanyhardshipordamagesthatmaybefallthemafterundertakinginformationdescribedherein.Additionally,theinformationinthefollowingpagesisintendedonlyforinformationalpurposesandshouldthusbethoughtofasuniversal.Asbefittingitsnature,itispresentedwithdatedassuranceregardingitsprolongedvalidityorinterimquality.Tradestampsthatarementionedaredonewithdateswrittenconsentandcaninnowaybeconsideredanendorsementfromthetradestampholder.

IntroductionCongratulationsondownloadingPythonProgrammingandthankyoufordoingso.ThefollowingchapterswilldiscussthetechniquesthatyouaregoingtousewhenyougetstartedwithprogramminginPython.Pythonisaprogramthatisgoingtobeoneofthebestprogramstostartwithwhenyouarewantingtolearnhowtowriteprograms.Programmingisnoteasy,soyouaregoingtoneedtobepatientwithyourprogrammingorelseyouaregoingtoendupmessingupandhavingtogobackandredoeverythingallthetimewhichisgoingtoresultinyoumostlikelywantingtoquitbeforeyoufinallygetintothemeatoftheprogram.Thereareplentyofbooksonthissubjectonthemarket,thanksagainforchoosingthisone!Everyeffortwasmadetoensureitisfullofasmuchusefulinformationaspossible;pleaseenjoy!

Chapterone:Python … .ASnakeorAProgramPythonisacodethatyouaregoingtowritewithonanycomputerthatyousodesiretouse.Theonlythingthatthecomputerisgoingtoneedistheabilitytowritecode.Asitwassaidintheintroduction,Pythonisagreatprogramminglanguagetostartwithbecauseitiseasytoreadandwriteforthedeveloper.So,ifyouhavetogivethecodethatyouhavewrittentoanotherprogrammer,theyaregoingtobeabletofixitandevenkeepwritingonitwithouthavingtoworryaboutscrewingupthecodebecauseitisnotgoingtobehardforthemtounderstandwhatitisthatyouarewantingtodo.ItiseasytoonlythinkofthesnakewhenyouhearthewordPythonbecauselet sfaceit.Thesnakeishuge,anditcankillyouwithoutmuchthought.However,theprogramPythonwascreatedafteracomedyshowthatthedeveloperoftheprogramenjoyedwatching.TheprogramisgoingtobeeasytoworkwithsinceitisavailableacrossmanycomputersandisnotgoingtoforcemetoconvertmycodejustbecauseIamonadifferentcomputer.Notjustthat,butwhenIwritewithPython,IamgoingtoprettymuchbedoingthesamethingIwouldbeifIwaswritingdatedwhatwasgoingoninmyheadonapieceofpaper.Pythonisextremelyuser-friendlyandmakesittowhereyoudonothavetodotoomuchworktogetthedatainputthatyoudesire.Sometimeinthe90 sateamsteppedupanddecidedthattheywouldmonitortheprogramandfindanybugsthatwerehidingdatedinthecode.Becauseofthis,supportthatIneedisgoingtobeeasilyavailableonthePythonwebsitewhichiskeptuptodatebythePythonSoftwareFoundation.PythonlikemostotherprogramscomesindifferentversionsandevenhasdifferentprogramversionsofPythonforthosewhoprefertouseprogramssuchasJava.PythonhasalsomadeittowherethereisaC#languagethatiswrittenmuchlikePythonandworksthesameexceptthatitisinadifferentlanguage.ThereisoneprimarylanguagethatPythonuseswhenitistryingtointerpretcode.Whileyoucan

useotherlanguagestowritecodeinPython,theyareallgoingtointeractwiththeprimarylanguagesothatitissimplefordeveloperstouse.ThePyPyprojectwascreatedsothatotherdeveloperscanhelpmaketheprogrambetterforthosewhoareusingitandthosewhowanttouseitinthefuture.AnythingthatIcansaveonmycomputerisgoingtobeabletobeputintoPythonforprocessing.AlotofthewebsitesthatweuseonaneverydaybasisaregoingtobedevelopedwithPython.Theydonotevenhavetobewebsitesthatweusebecausetherearealotofgovernmentandnon-profitwebsitesthatareusedanddevelopedbyPython.SincePythonisalanguagethathastobeinterpreted,IwillnothavetohaveanyotherprogramsopenlikeifIwasworkingwithadifferentlanguage.Pythonwasmadetobeanomenclatureprogramsothateverythingyouneedtoworkwiththeprogramisintheprogram.Pythonisunlikeanyotherlanguagethatyouaregoingtoworkwith.Thecommandsaredifferent,andtheprogramevenrunsdifferently.PythonintherealworldTherearejobsdatedthereintherealworldthatyouaregoingtobeabletousePythonfor.Thingssuchasdevelopingwebpages,creatingartificialintelligencedevices,workingwithdatabases,andmakingvideogames.EachsectionthatyouareabletousePythonwithisgoingtobeadifferentlevelofPythonuse,butitisallgoingtoworkthesame.

Chaptertwo:InstallingPythontoYourComputerWindowsVersionThefirstthingthatyouneedtodoisselectthelatestversionofPythonfromthewebsite.ThereisapackagethatisopenfortheadministratoroftheWindowsoperatingprogramsothatitwillautomaticallydownloadPythonlikeitissupposedtobe.Dependingontheversionthatyoudownload,theprogramisgoingtobedownloadedtoitsownfolder.YouareonlygoingtohaveoneinterpreterevenifyoudownloadseveralversionsofPython.Differentversionsarenotgoingtointeracttogethersoyoucanusethemseparatelyfordifferentcodes.YoucanjustenterthepathtitleforPythononceandmakeitasthefilepathsothatyoudonotalwayshavetofiguredatedthefilepathbecauseifyoudothis,youaregoingtoenduphavingalotofcodetofiguredatedallthetime.EnvironmentscanbesetupfordownloadingPythonbyusingPowershell.Powershellisacompletelydifferentlanguage,andifyouarewantingtouseit,youaregoingtohavetolearnit.TherearesomesimilaritiesbetweenPythonandPowershell.However,theyarestillgoingtobetwocompletelydifferentlanguages.Theseconddirectoryscriptreceivescommandfileswhencertainpackagesareinstalled,sothisadditionhelpsalot.YoudonotneedtoinstallorconfigureanythingelsetousePython.Inparticular,youshouldalwaysinstalltheSetuptoolssoftware,asitmakesitmucheasierforyoutouseotherthird-partyPythonlibraries.

Chapterthree:WhyPythonShouldbeLearnedPythonisaprogramthatmakesittowhereyoudonothavetocompileitbeforeitcanbeexecutedbytheprogram.Pythonisalsoobject-oriented(inwhichitispossibletointeractand/orexecutemultipleprogramsatonce).Pythonisoneoftheeasiestanduser-friendlyprogramlanguagesaround,asitiscreatedtolookprettyrather thanugly,explicit insteadofvague,andeasy toread. It isstillcomplex likeotherprogramminglanguages,butwithpracticeanddiligenceinthematerial,itwillbecomesimpletouse.If youwant to learn how to code, youmight aswell use a program that is free and simple. Itthrivesonbeingassimpleaspossible,andyoucanevenmakeafewshort-cutcommands.Forexample,thecommandforEnumerate(whichcanreturnanenumerateobjectlikealist)is:l=0forobjectinoperation:stampl,objectl+=1Adifferentcodingoptionis:forl,objectinenumerate(operation):stampl,objectAndEmulatecaneventakeonasecondargumentlikeso:>>>list(enumerate(x,y,z))[(5,'x'),(4,'y'),(3,'z')]>>>list(enumerate('l,m,n',2))[(9,'l'),(8,'m'),(7,'n')]ThecommandsthatyouuseinPythonaregoingtobeeasytounderstandthankstohowPythonis

setup.Youarenotgoingtohavetoworryaboutsomeoneelsenotunderstandingwhatyouwanteddonewithyourcodebecauseitisallgoingtobelaiddatedfortheminblackandwhite.WhilemasteringtheuseofPython,onecannoticethatyou llbeabletocodesomeofthemorecomplicatedscriptsthatusuallytakehoursorminutestoprogram.WithinthescriptinglanguagesofPython,therearetargetsthatmakeprogrammingvariantsfastandeasy.Thisway,shouldyouwanttocreatescriptsthatsimplifyeverydaywork,Pythonistheprogramofchoice.Whileitmaynotbeimportant,itisagreatassetifthescriptinglanguagesareeasytoread.Forexample,ifyouhappentoberunningoffthePerlscriptinglanguages,thecodecanlookalotlikehieroglyphics.However, Python can descramble the code and make it t where it is more likely for you torememberwhatyoursourcecodedoes.Pythonhas a large set ofmodules that canhelpyouwith just about anythingyouneedwhen itcomestolanguage.Thedownsidetothisisthatyouneedtoelaborateinordertofullybeabletodiscovertheinsandoutsofsomeofthemorecomplexmodules.ThebiggestthingthatmakesPythonsogreatisthatitcanbecrossplatform.Whatmakesthissousefulisthatseveraloperatingprogramsareusuallyusedwhenworking.Pythonisabletorunonanymachineandthereforeyoucanrunwhateverscriptsyoudecidetocreatealmosteverywhere.However,PythoncanalsocrossplatformwithoneslikeQtorGUIs.ThiscanresultinanyGUIsthat you create not having to be readjusting the source code each time you switch to a newmachine.

Chapterfour:HowtoUsePythoninDifferentWaysYouhaveinstalledPythononyourcomputer.Yay!Nowyouaregoingtoneedtouseit.ButhowareyougoingtousePython?Pythonhassomanydifferentwaysthatyoucanuseitthatyouaregoingtohaveseveralthingsthatyoucanchoosefromsothatyoucangettheresultsthatyouarewanting.AsyoulearnPython,youaregoingtofindthatitisimportanttounderstandhowtheprogramisgoingtoworkwiththecommandsthatyouputintotheprogram.Ifyoudonotunderstandhowitallworkstogether,thenyouaregoingtoenduptakinglongertowritethecodethatyouhaveinPython.CalculationsStepone:openPythonandinsertthewordPythonintothecommandprompt.Youaregoingtobeabletopressentersothatyoucanforcetheinterpretertoworksothatyoucanuseit.PythonshouldbemovedintothecommandpromptsothatthedirectoryforPythoninvokestheinterpretertoworkthewaythatitissupposedto.Steptwo:oncetheinterpreterhasbeenopened,themostbasicofequationscanbeplacedintotheprogram.Ifyouendupseeingapoundsign,youaregoingtohavetoreenterthecodebecausetheprogramneveracceptedit.Stepthree:ifIwanttousethepowerswhenIamputtingcodeintoPython,IamgoingtousedoubleasterisksthatwaythatPythoncanbeusedforlargeramountsthanwhatyoumaybeusedtoworkingwith.Stepfour:variablesaregoingtobetiedtoothersinPythonwhenyouaredoingmath.TheequalssignisgoingtobethesymbolthatIusetoassignvariablestoamounts.Stepfive:onceallthecalculationshavebeenfinished,theinterpreterwillbeclosed.Youcancloseitbyenteringquit()andtheprogramwillbeclosed.

ThefirstcodingprogramStepone:thefirstprogramthatyouaregoingtocreateisgoingtobethemostbasicofprogramsthatyouaregoingtouse.Thisisgoingtoshowyouhowtousetheinterpretersothatyoucanmakesurethatitisworkingcorrectly.Steptwo:whenyouareenteringcodesintothecommandprompt,youaregoingtoenterinfigureandthenthecodethatyouwanttoputintotheinterpreter.Stepthree:theprogramhastobetestedtomakesurethatitisworkingcorrectly.FirstIamgoingtoputinatitle.ExampleFigure( Thisisgoingtobethetitleformyprogram )AnyannouncementthatIcreateinPythonisgoingtoneedtohaveasetofdoublequotesplacedarounditsothattheprogramreadsitcorrectly.Stepfour:oncethetestinghasbeencompleted,thenIcansavemyprograminordertoworkonitlaterone.IamgoingtoneedtomakesurethatIaddontheextensionof.pytoallofmyPythonrelateddocumentssothatIknowthatitisPythonandnotadifferentlanguagethatIcouldbeworkingwith.Stepfive:thecommandpromptisgoingtobereopenedandnowIcanreopenmyprogramoncemore.ThisisgoingtoensurethateverythingisworkingproperlysothatIcanseeifanycodethatIenterintotheprogramisgoingtoberuninthewaythatitissupposedtoberun.ProgramsthataremoreadvancedStepone:therearegoingtobecircumstancesastohowaprogramruns.Thecircumstancesthataresetintoplaceareknownasthecontrolflow.ThecontrolflowisgoingtobehowIamgoingtobeabletocreateotherprogramsthatwillworkthewaythattheyaresupposedtodependingonthecircumstancesIputintoplace.

ThewhileannouncementisoneofeasiestreportsthatIamgoingtobeabletowrite.Steptwo:functionsaregoingtobedefinednomatterwhatfunctionIamusing.ThefunctionsaregoingtoneedtohavetitlessothattheycanbeusedlaterwiththeprogramsthatIamworkingwith.Stepthree:thecontrolflowisgoingtosetupthecircumstancesthataregoingtobethepremiseofhowtheprogramwillwork.Theytelltheprogramwhatitisandisnotallowedtodo.Stepfour:themathematicalsymbolsthatyoulearnedwhenyouwerelearningmathinschoolaregoingtobeusedinPythonaswell.Stepfive:youcanalwayslearnmoreaboutPythonbecausetheprogramisalwaysevolvingthankstothosethatareworkingtomakeitthebestprogramthatisdatedthere.

Chapterfive:DesigningaWebsitewithPythonTherearenumerousthingsthatyouaregoingtobeabletodowithPythonandcreatingawebsiteisoneofthem.WhilewhatIputintoPythonisnotgoingtoalwayscomedatedthewaythatIwantittocomedatedthefirsttime,IamgoingtobeabletouseitasatemporaryprogramforanyprojectthatIdecidetomakewithPythonthatwaythatthefinalprojectisgoingtobethewaythatIwantittobeintheend.GoogleisonewebsitethathasbeenmadewithPythonthereforeitiseasytoreadandunderstandforprogrammersanditiseasytousefortheircustomers.Besurethatyouarealwayssavingyourwork!Ifyoucannotwriteanentireprograminonesetting,thenyouneedtosaveitsomewhereelseonyourcomputersothatyoucangettoitlater.Itisrecommendedthatyourprojectbeputsomewherewhereyouaregoingtobeabletogettoitintheeventthatyourcomputercrashesandyoucannotretrievethefilesonyourharddrive.ExampleImportdirectoryProgram=directory(_titleofthedirectory_)Theprogram.path( / )Determinefirstpage():Result thetitleofthedirectoryisgoingtoenduphereThe_titleofthedirectory_== _endofthecode_ :Program.work(fix=thisisgoingtobetruebytheprogram)

Thedirectorythatisimportedisgoingtoalwaysbethefirstlineofcodesothattheprogramknowswhatitisdoingandthecodethatyouareenteringisrunningoffthecorrectframeandnotthedefaultone.Intheeventthatwhatyouarewantingtoimportisnotinstalled,youaregoingtoreceiveanerrorcode.Thisiswhereyouaregoingtohavetoinstallthelibrarysothatyourprogramworksproperly.Toinstallthedirectoriesthatyouneedyouaregoingtoneedtoinsertthepipinstallintothecommandprompt.Itwillthenbeinstalledandthewebsitethatyoucreatedisgoingtorunthewaythatyouwantitto.Byputtinginlocalholder:6000willmakesurethatthewebsiteisseenonthebrowserthatisgoingtoberunningit.Whenyoulookatthewebsitethatyouhavecreated,youaregoingtoseethatitisworkingbutitisnotgoingtolooklikeanyotherwebsitesthatyouhavebeenonbefore.Youaregoingtoneedtouseadevelopertocreatethewebsitedesignthatyouarewantingaslongasthecodethatyouenterintothecommandpromptworksthewaythatitissupposedto.Pythonneedstobeabletohandleanyrequestthatyoumakeofitanditneedstotakenoteoftheamountoftrafficthatyouaregoingtobegettingonyourwebsite.Webpagesaremadespecificallyfortheamountoftrafficthatyouaregoingtogetbecauseifyourwebsiteisnotstable,thenitisgoingtoendupcrashingcausethecodeisnotthewaythatitshouldbe.Pythonisgoingtohelpyoucreatemultipledocumentswiththeproperdirectoryinuse.Oncetheframeworkisloaded,Pythonisgoingtocarrydatedthecodethatyouwantcarrieddatedanditisgoingtohelpyousothatyoucanfocusonfixingyourcodetomakesurethatyourcodeworksthewaythatyouarewantingitto.Oncethedocumentshavebeenimportedandyoucancreateatypesothatyouhavehelpinmakingyourwebsite.Newlinesaregoingtobedefinedbythefunctionsthatyouuse.Youaregoingtoneedtosetseriesofcodesothattheyrespondtothefunctionthewaythatitissupposedto.Thiswillmakesurethatthehomepageandotherpagesthatareonyourwebsitearegoingtolookhowyouwantthemlook.Notonlythat,buttheyaregoingtomakesurethatyourwebsitedirectspeoplethewaythatyouwantthemtogo.

Youaregoingtoneedtochangeyourcodeupjustalittlesothatyourcodegoestotheproperpage.Itdoesnotmatterhowmanypagesthatyouhaveonyourwebsite,justaslongasyourcodeiswritteninthewaythatyouwantittoappear.Allofthecodethatisplacedintheprimaryfunction,youaregoingtowriteitthesamewaythatyoualwayswriteyourcodeanditisgoingtobebroughtinfromexternalsourceswhileyouarestillworkingonthepropertitlepage.Ifyourcircumstancesendupbeingsatisfied,youaregoingtonowhavecompletecontroloverthescriptandthewaythatitbehaves.Youarealsogoingtocontrolhowyourusersaregoingtointeractwiththescriptthatyouhaveputintotheprogram.Yourcircumstancesneedtobefoundastrueandvalidtoensurethatyouarenotgoingtohavemanyerrorsplacedinyourcode.But,ifthereareerrors,thenyouaregoingtoneedtouseaprogramthatisgoingtotracetheerrorsbacktowheretheproblemstarted.Iftheparametersareinvalid,thenyourcodeisnotgoingtorun.MostofwhatyouseeonawebpageisHTML,andtheHTMLisgoingtohavetobebroughtinfromanexternalcodingsourcesothattheplainwordsischangedtoHTMLandbringsuserstoyourpage.TheHTMLpagesaregoingtorespondwithafunctionthatisknownasrender_figure.Thedifferentthingsthatyouwanttoshowuponmypagewillbedonewithspecificfunctionssothatyourpagebecomeswhatyouarewantingittodo.BecausePythonissoversatile,youareabletousemultiplecodingtricks.HTMLisgoingtobestartedinanemptydocumentandhavetheextensionof.htmlsothatitisdifferentthanthePythonfiles.Afterthepage,hasbeencreated,youaregoingtobeabletoenterthecodethatyouwant.Example<!figureofdocument:html>

<htmlcode><bodyofthecode><headingone> Words </headingone><body> words </body></endofthecode></htmlsothattheprogramknowsthatthisistheendofthehtml>TherearesomethingsaboutHTMLthatyoumayfindinterestingforthewebpagesthatyoucreatesothatyouarenotjustputtinginseriesofwordsthatarenotpleasingforyourusers.AsyouworkwithHTMLyoushouldremember:

-DocumentshavetobeginandendwithHTMLsothattheprogramunderstandthatitneedstochangethecodethatyouenter.-ThedocumentsforHTMLhavetostartwithadeclarationsothatitcanbeidentifiedastowhatkindofdocumentyouarecreating.-Whenthecodeisnotputbetweenthebodytags,itisgoingtobeplacedasJavaScriptcodeorevenCSS.

Movingbacktothedirectorythatyouareworkingwith,foldersaregoingtobecreatedtoseparatedatedthedifferentcodefiguresthatareinyourdocument.Anycodethatisnotplacedintothecorrectframe,thenitisgoingtostayinPythoncodeinsteadofbeingconverted.HTMLcodelookssimilartothedirectorycode,butitworkswithHTMLinsteadofPythoncode.ExampleImportdirectory,render_figure

Program=directory(_wordsforwhateveryouwantyourpagetobetitled_)Directory.path( / )Explaindatedreach():Resultrender_figure(datedreach.html)If_words_== _endofthecode_ :Program.file(parameter=valid)Theversionofthecodethathasbeenupdatedisgoingtousethefunctionthatwehavetalkedaboutearlier.NowthattheHTMLcodeisinsideoftheframeworklikeitissupposedtobe,thenyoucanhaveaccesstoitbetterthanyoudidbeforeandyouaregoingtobeabletocontinuewithyourwebdesignwithouthavinganyissueswithit.BeingthatthedocumentsforHTMLareinsideoftheframework,thefigureisgoingtoresponddifferentlythanitdidbeforeeachtimethatauservisitstheURL.Tocreatepages,youaregoingtoneedtocreateHTMLdocumentseachtimesothattheyareplacedintotheproperfolder.Example<figureofdocumenthtml><htmlcode><bodyofthecode><headingone>words</headingone><body>thisiswheremoreofyourwordsisgoingtogoforyouruserstosee</body>

</endofthecode></endofthehtmlcode>ItisatthispointthatyouneedtorenderthedocumentsfromPythontoHTMLtouseitasitshouldwiththefunctionsthatareplacedintotheprogram.ExampleFromthedirectoryimportlibrary,render_figureProgram=directory(_enterinsomeofyourwordshere_)Program.path( / )Explainglass():Resultrender_figure( glass.html )Program.path( /glass/ )Explainsoda():Resultrender_figure(soda.html)If_words_== _anotherpartofyourwords _:Program.run(parameters=true)Afterthelastlineofyourcodehasbeenputintotheprogram,youcanrunthatpagesothatitopensupasanewpageforyourusertointeractwith.LateryouaregoingtobeabletoaddinsomeCSSsothatthepagehassomecolorandthenissetuptolookthewaythatyouwantittolook.Makeituniquethoughsothatitlooksdifferentthanotherwebsitesthatareontheinternet.

Chaptersix:TheManyVersionsofPythonVersion1.0In January the very first version of Pythonwas released back in 94. But, it had very little toactuallydowiththeprogramthatweknowtoday;ithadsomeofthemorebasicfunctions,butitwasn tuntilahackerhelpedVanRossumtofixthebugsthathefoundtomakeitabetterprogram.Whiletalkingabouttheprogram,thedeveloperoftheprogramdidnottryandtakecreditforthechangesthatweremade,insteadhegavecreditwhereitwasduetothehackerwhohadsubmittedthepatchesforwhathehadfoundwaswrong.Working with CWI, a new version of Python was released. . Even after this, Rossum wouldcontinuetoworkonPythonasheworkedforCNRI,RossumreleasednewversionsofPython.WhenanewPythoncamedated,newfeatureshadbeenadded toPython.Amongthesechangeswasthemodula3thatinspiredthekeywordargumentsaswellasthebuiltinsupportthatallowedtheusertousecomplexnumbers.Therewasalsoallowedmorecomplexnotestodothingswhichwereearlierbypassed.WorkingatCNRI,Rossum launched theCP4EotherwiseknownasComputerProgramming forEveryone.Itwasintendedinmakingprogrammingeasierforpeoplewhoonlyhadthemostbasicknowledgeinprogramminglanguages.Becauseofitscleansyntax,PythonservedacentralroleinCP4E.DARPA funded the CP4E project.When 2007 came around, the Cp4E project becameinactivewhenPythonreacheddatedtonon-programmers.BeOpenThePython development team createdBeOpen.com in order to createBeOpen in 2000.CNRIpressuredthereleaseofversionof1.6ofPythonbereleasedsohardthatthoseworkingonitgotupandquit..Thereasonthat1.6wasnotreleasedwasbecauseitwouldhaveoverlappedwiththereleaseofversion2.0.VersionTherewasonlyoneversionofPythonthatcamefromtheBe

Opencompany.OnceVersion2wasputdatedforthenational,thePythondevelopmentteamalongwithvanRossumjoinedDigitalCreations.Eventuallyversion1.6didgetreleasedinordertoincludeanewwarrantwasputintoplacethatwas longer than the lastonewasused. With thisnewcontract, therewasanewitemthatwasplacedwithinitstatingthatitthenewPythonwasnowtobeundertheState slaws.Becauseofthis,thisbroughtalegalfightinsothatthecompanycouldchoosewhotheyfellunder.BeOpen,CNRI and FSF soon negotiated that Python s free softwarewarrant bemadeGPL compatible.Thereforeversion1.6.1wasreleasedbutsomeofthebugsfrom1.6werefixedaswellashavingthenewwarrant.Version2.0WithSecondversionbeing released theanew list functionwas introduced.This functionwasbasedoffofalanguagethatwasdevelopedbytwootherpeople.Atfirst,Thewaythatthecodeiswritten in the program was similarly written to Haskell s program, but did not include thepunctuationthatHaskellseemedtopreferwhilePythonpreferredthealphabetickeywords. 2.0alsoincludedagarbagecollectionthatallowedtheprogramtocollectreferencecycles.Justasversion1.6.1,version2.1wasnowunderPSF'scontrol.Withthis,thecodeandfilesaswellascertainspecificationswereaddedatwhenthenextversionofPython2camedated.2.1wasbelonged toPSFwhichwasa isa foundation thatwasstarted in01.Withachange to thelanguage specification, the release had included the support of nested scopes and other staticscopedlanguages.With2.2,allofPython sfigureswerewritteninCaswellas the typeswereputwasput intoagroup. The this change caused the program to become purely object oriented.Aswell as thisbeingchanged,generatorswerealsoaddedthatwereinspiredbyIcon.InNovemberof2014,Pythonannouncedthatversion2.7wouldbethesupportuntil2020.Withthisnews, itwasconfirmed that therewouldbenoPython2.8andanyPythonuserswouldbeforcedtochangetothenewversionassoonasitcamedated.Version3.0

Version3becameknownasthe3000Python.Thisversionwascreatedinordertofixsomeofthemore serious the mistakes in the program became. Although, some Python s patches that thedevelopment team wanted could not be kept as well as Python retaining the backwardscompatibility with the 2.x series. Ultimately, Python 3was created in order to reduce featureduplicationsaswellasremovingtheoldwayofdoingthingsandmakingthingseasierontheirprogramusers.

Chapterseven:PythonandJava...WhataretheDifferencesPython and Java are two well known titles that programmers use. But, which one is actuallybetter?Ultimately,Iwouldsaythatitisuptotheprogrammerandtheirpreferences,buttherearepeoplewhowillargueandsaythatPythonisbetterbecauseofhowquickPythonistouseandthewaythatitiseasytoreadforevensomeonewhoisnotgoodatreadingcode.But,let slookattheactualprogramsandtheirdifferencestoseeifwecanfindaclear winner.Programmersusethreeprimarylanguagecharacteristics.WhileusingJavathereisthestaticfigured.Withthis,allvariabletitlesaswellastheirfiguresmustbedeclared.Ifyouassignanobjectof thewrongfiguretoavariablewill triggerafigureexception.Ultimately,thismeansthatJavaisastaticfiguredlanguage.TheJavaobjectcontainercontainsobjectsofamoregenericfigure.ForexampleObjectcannotbeheldprimitivesuchasint.Shouldyouwanttostoreansumwithavector,youwouldfirsthaveto convert the sum to an integer. From there retrieving an object from a container, it will notrememberthefigureandwillbecastintowhateverfigure.Verboseisanaboundinginwordsorcontainingmorewordsthanisactuallynecessary.Notcompactinitscoding.Forexample:nationaltypeThisIsMe{nationalstillemptyprimary(Series[]para){Program.dated.stampln("Thisisme!");}}Pythonon theotherhand isdynamically figuredwhichmeans thatPythonwillnevermakeyou

declareanything.Whenanassignmentreportbindsatitle toanobject thentheobjectcanbeofanyfigure.Shouldatitlebeassignedtoanobjectofonefigure,thenitmaylateralsobeassignedtoanotherfigure.Concisewhichmeansthingsareexpressedinasfewwordsaspossible.Thisindicatescleancutbrevity.Therefore,itiseasiertoread.Compact. In other words, there are fewer word and even fewer chances for mistakes to beskippedover.

Example:

stamp"Thisisme!"

Hereare twomoreexamplesofhowJavaandPythonaredifferent.You llnotice that the JavacodeismorecomplexandhardertoreadthanthePythononeis.Also,whilePythonislongerthantheJavaone,itlookscleaner.Javaexample:

sumyourCounter=6;SeriesyourSeries=Series.valueOf(yourCounter);if(yourSeries.results("6"))...

//stamptheintegersfrom5to10for(sumd=6;d<11;d++){Program.dated.stampln(d);}Pythonexample:

yourCounter=6yourSeries=str(yourCounter)ifyourSeries=="6":...

#stamptheintegersfrom5to10fordinrange(5,11):stampdSaythattheapplicationyou remakinghas15typees.WhileusingJava,eachtop-leveltypehastobedefinedwithinitsownfile.So,iftherearefifteentypees,thentherewillbefifteenfiles.But,whileusingPythonyourtypescanbedefinedwithinonefile.But,itmightmakesenseforyoutoseparateyourtypesintofourtofivefiles.Java:

nationaltypebooks{privateSeriesbooktitles;privatesumnumberofbooks=9;privateSeriesbookstatus="fair";

//---------book#1------nationalbook(Seriesbooktitle){this(booktitle,3);}

//---------book#2------nationalbook(Seriesbooktitle),sumnumberofbooks){this(booktitle,numberofbooks,"nine");}

//---------book#3------nationalbook(Seriesbooktitle,sumnumberofbooks,

Seriesninebooks){this.booktitle=booktitle;this.numberofbooks=numberofbooks;this.bookcircumstances=bookcircumstances;}...

Python:

typebook():

res__init__(self,booktitle,number=5,circumstances="fair"):self.booktitle=booktitleself.numberofbooks=numberofbooksself.bookconditoin=bookcircumstances...

Chaptereight:SeriesSetup

SeriescontainconstantsandtypesthatyouaregoingtofindasusefulwhenyouareusingserieswithPython.Mostseriesaregoingtoholdsomekindoflegacyfunctionsthatareonlygoingtobeusedwhenyouarecreatingseries.Pythonhasseriesfiguresthatarebuiltintoitsprogramminginordertosupportthesequencingfiguretechniques.

Inordertosetupthedatainputonseries,youaregoingtouseatemplateorthepercentsign(%)operator.Pythonhastoolsthatarebuiltintotheprogramsothatyoucansetuptheseriessothattheyaregoingtoworkthewaythattheyaresupposedto.ThetypesinPythonareUnicodeandstrandtheywereputintotheprogramsothatyoucandealwithvariablesthataregoingtocreateamorecomplexserieswhenyouarescriptingit.Youwillneedtousethestr.setup()functiontogetPythontosetupyourseries.

Thetypesetupsaregoingtobeinsideofthemodulethatistherefortheseriessothatyoucancustomizeanyseriestowhatyouaretryingtodo.Thatwayyoucanmanipulatethewaythattheseriesisgoingtobehavebyusingspecificfunctionsandtechniquesthataregoingtobeusedwithyourseries

Typeseries.Scripter:thisisthescripterthatisgoingtofollowthenationaltechniques.

Setup(setup_series,*args,**gars):theprimaryAPImethod.Thistakesyourseriesthatyouhavejustsetupaswellasarandomsetofkeywordargumentsandpositions.Thisisjustawrapperforyoursetupseriesthatusesvsetup().

Thescripterisalsogoingtohelpdefineavarietyoftechniquesthatyoucanusetoreplacethesubtypes.

Parse(setup_series):youaregoingtocrossthesetupseriesandthenreturntheoperationtuple(literal_words,prompt_title,setup_spec,change).Usingthiswithvsetup()isgoingtobringtheseriesintochangepromptsorliteralwords.

Anyvaluethatisplacedintothetuplewillrepresenttheliteralwordsthatwillbefollowedbutasinglechangeprompt.Ifyoudonothaveanyliteralwords(whichcanenduphappeningifyouhavetwochangepromptsconsecutively),thenyouliteral_wordsisgoingtobeaserieslengthofzero.Shouldyounothaveanychangeprompt,thentheamountsprompt_titleandsetup_specaswellaschangearegoingtobeNone.

Get_prompt(prompt_title,args,gars):whentheprompt_titleisrestoredbyparse(),youwillconverttheobjectsothatitcanbesetup.Atupleisgoingtoreturn(obj,used_lock).YourdefaultversionwilltakeyourseriesthathasbeendefinedbyPEP3101whichcanbefoundat:https://www.Python.org/dev/peps/pep-3101.

Theseformsareeitherlabel.titleoreven 0[title] .ArgsandGarsaregoingtobepassedwiththevsetup()sothatyourreturnvalueused_lockisgoingtohavethesamedefinitionasyourlockparameter.

Get_value(lock,args,gars):youaregoingtobeabletoretrieveanypromptvaluethathasbeengivenwithinalist.Thelockargumentisgoingtoeithergiveyouaseriesoraninteger.Inthecasethatyougetaninteger,youwillseetheindexforthepositionalargumentasitisinargs.But,ifyougetaseries,thenitisgoingtorepresentthetitledargumentingars.

Iftheparameterforargsissetinyourlistofpositionalargumentsforthevsetup()thenthegarsparameterwillbesettothekeywordargumentsthatareinthedictionary.

But,foranyprompttitlesthatarecompound,thenthefunctionsareonlygoingtocallforthefirstcomponentoftheprompttitle.Thefollowingelementsaregoingtohandlethestandardtechniquesandoperationsusedforindexing.

Ifyourpromptexpressionis 0.title thenyourget_value()isgoingtoneedalockargumentthatequals0.Thetitlewillbelookedupaftertheget_value()isrestoredbycallingthegettatter()functionthatisbuiltintoPython.

Whenthekeywordandindexaregoingtorefertoanobjectthatdoesnotexistthen,thelockerrororindexerrorisgoingtoberaisedtoalertyouthatthoseobjectsdonotexist.

Check_unsued_args(used_args,args,gars):whencheckingforanyargumentsthathavegoneunused,youaregoingtousethismethod.Theargumentsthatyouhavesetupwithallofyourargumentlocksaregoingtorefertotheseriesthathasbeensetup.Thisincludesthepositionalarguments,integers,andseriesthatwereusedforanytitledarguments.

Theyarealsogoingtoreferenceanygarsorargsthatwentthroughvsetup.Anyunusedargsaregoingtobecalculatedusingtheparameters.Check_unused_args()willraiseanexceptionshouldthecheckfail.

Setup_prompt(value,setup_spec):theglobalsetup()isthesamethingassetup_prompt().Thismethodwasmadesothatsubtypeswereabletooverrideit.

Convert_prompt(value,change):thevaluethatisrestoredfromget_prompt()willthenbe

converted.Anydefaultversionisgoingtoknowthatstr(s)orrepr(r)aswellasascii(a)arethechangefiguresthatareusedbyPython.

Chapternine:DetailandDatainput … HowDoYouAcceptThem?

AnydatainputthatcomesfromPythonisgoingtobeintheformofreadableandwritablenotesthatcanbeusedlaterone.Themostbasicofdetailanddatainputlessonsisusuallythehello.pylesson.However,youcanusewhateveryouwanttofiguredatedthedetailanddatainputofPython.

Itseemsalittleboring,butitisthebestwayforyoutounderstandhowtodetailthingsintoPythoninordertogetareadabledatainput.

LookatPythonlikewordsmessagesthataresentbetweenyouandyourfriends.Youaregoingtoputsomethingintothewordsboxandwhenyouhitenter,youaregoingtoseewhatyoutypeddatedonyourscreenaswilltherecipientofyourwords.Thisisyourdatainputbecauseyouhaveenteredsomethingandgottenthesamethinggivenbacktoyouinamorepermanentmanner.

Thisistheresultofandetailprogramthathasbeenwellbuilt.

Theinformationthatyouputintotheprogramhastobestampedwithparameterssothatitknowswhatitissupposedtodo.Andyouaregiventheproperdatainput..

Withoutparameters,yourusersarenotgoingtoknowwhatitisthatyouarewantingtheprogramtoduebasedonwhattheyareputtingintotheprogram.Ifyouruserknowswhatkindofnotesyouarewantingputintotheprogram,thentheyaregoingtobeabletogiveittoyouandwaitforaresponseastowhatyouarewanting.

Forexample,youaregoingtoruntheprogramthatisgoingtoorganizeyourbookswithoutanynotes,tryanddeterminewhatitdoes.

Booktitle=detail( Enterthetitleofthebook: )

author=detail( enterthetitleoftheauthor: )

genre=detail( Enterthebook sgenre: )

Stamp(author, wrotethisbook, inthisgenre)

Notesthatisputintotheprogramisgoingtobeexecutedthesamewaythatitisdetailedintotheprogram.Thisistheeasiestwayfortheprogramtoberunbecauseitflowswithwhatisentered

intotheprogramanditiseasiertoread.But,youareabletochangethisdependingonwhatyouputintotheprogramsothatitexecutesitinadifferentmanner

Twofunctionsaregoingtobedesignedtotakenotesdirectlyfromyoutheuser.Thosefunctionsaredetail()andraw_detail().

Raw_inpu()isgoingtobewhentheprogramaskstheusertoenterinaseriesofnotesandthenitreturnsthesameseriesthatyoufiguredin.Itcanalsotakeanargumentthatyouenteredanddisplaysitasapromptbeforeanyinformationisenteredbytheuser.

Example:

Stampraw_detail( whatisthetitleofthebookthatyouarecurrentlyreading? )

Thedatainputisgoingtosaywhatisthetitleofthebookthatyouarecurrentlyreading<usernotesdetailhere>

So,toputtheuser scurrentbookintotheprogram,youaregoingtowanttoassignittoavariableofyourchoice.

Nowyourcodeisgoingtolooklikethis:d=raw_detail( whatisthetitleofthebookthatyouarecurrentlyreading? )

Thisiswhereyouaregoingtobeabletoenterinatitle.Therefore,ifyouarereadingWarandPeace,youaregoingtocallthatyourdvariable.ThePythoncodeisnowgoingtolooklikethisstamp Yourbooktitleis +d

AndthedatainputforthiswillultimatelybeThebookthatyouarereadingisWarandPeace.

RegulardetailisgoingtousetheseriesnotesfromarawdetailandevaluateifitwasaPythonprogram.

Thedatainputisgoingtocomefromtheinformationthathasbeenputintotheprogram.TheinformationthatisputintoPythonisstampedoverthequestionbeingstampedbecausethequestionisnotthevariable,theinputfromtheuseristhevariable.

Chapterten:IfReports

Tosaveyourselfaheadachewhenyouareworkingwithifreportseries,youaregoingtowanttousesimplemathovercomplicatedequations.

Forexample:

X=sum(raw_detail( Pleaseenteranumber: ))

Pleaseenteranumber:2

Ifd<1

d=1

Stamp theresultneedstobechanged

Elifd==6:

Stamp Single

Else:

Stamp false

Thisisaheadachewaitingtohappencorrect?Instead,let sbreakitdownsothatitisnotgoingtobesocomplicatedforyoutounderstandandthatwaywhenyouarewritingyourownifreports,theyaregoingtocomeeasierforyou.

Elifreallystandsforelseifandshouldbeemployedinexcess.Anif,elif,elifsequencewillonlybeaplaceholderforthecaseorswitchreportsthatyoucanfindinothercodinglanguages.

Ifreportsaregoingtobethesameasthemaththatyoulearnedinschool,however,thesymbolsthatyouknowaregoingtobeslightlydifferentbecausetheyaregoingtohavetobeabletoworkwiththeprogramandsincenotallofthesymbolsarestandard.

Lessthan<

Greaterthan>

Lessthanorequalto<=

Greaterthanorequalto>=

Equals==

Notequal!=

ThereshouldneverbespacesbetweenthesymbolsthatareusedinPython.

OpenuponeofyourtestfilesthatyouhaveforPythonandwiththisfileyoushouldtryandputindifferentamountssothatyougetdifferentresultsandcanseewhattheprogramdoes.

Thecodeyouaregoingtoputintothisfileis:

books=float(detail( Howmanybooksdoyouhave? ))

Ifthebooksis>7:

Stamp( Thereisonlyroomforsixbooksthatarethickbooks. )

Stamp( Mybooksarethinnovels. )

Thereportisinthemiddleofallthescriptthatyoujustwrotesothatyoucanknowthatyourshelfisnotgoingtobeabletoholdthatmanythickbooks.but,ifthebooksarethin,youcanputmoreonthere.

Increatingifreportsyourbasicsyntaxwilllooklikethisforeveryreport.

Ifcircumstances:

Reportthatisindented

Usuallysomethingisgoingtobedoneifyourreportistrue.But,ifyourreportisfalse,thennothingwillbedone.

Anotherexamplewouldbe:

price=float(detail( whatisthepriceofyourbiggestbook? ))

Ifthepriceis<=$19

Stamp( Thepriceisgoingtobe$20 )

Stamp( Thankyoufortheinformation. )

Shouldthebookbelessthannineteenbucks,thecustomerisprobablygoingtobuythebook.However,sincethebookisactuallytwenty,thentheyarenotgoingtobuyit.

Thisishowthedecisionsaregoingtobemadewith if reports.Theyareeasytomisunderstandifyouarereadingthemtooquickly,but,ifyoutakethetimetorememberwhatyoulearnedwhenyouwerelearningthedifferentsymbolsthatwerenotedpreviously,thenyouaregoingtobeabletofiguredatedexactlywhatisbeingsaidandwhatthedecisionisgoingtobewhentheequationissaidanddone.

Onelastexample:

Ifbooks<25:

move=newplace

#movethebookstoanewplaceontheshelf.

newplaceontheshelf=newplaceontheshelfforthebook

move=wherethebookswere+thenewplacethattheynowoccupy

chaptereleven:ErrorsandExceptions

Therearegoingtobeerrorcodesthatpopuponyouforthesimplereasonthatsomethingwasnotenteredcorrectly.Thereisalsothepossibilitythatthereissomethingelsegoingontothrowthaterrorcodedatedatyou.

Notonlythat,buttherearealwaysgoingtobeexceptionstotherulesofPythonandwhythingsareenteredindifferentlythanwhatyoumaybeusedto.

Inordertoknowhowtohandletheerrorsandexceptions.Youneedtoknowwhattheseerrorsandexceptionsareaswellaswhatcausesthemtoappear.Sometimestheerrorsaregoingtobeabletobeemptied,buttherearetimesthattheywillnotbe.Donotgetdiscouragedifyoucomeacrossanerrorcode,allyouneedtodoisgobackandfixwhatiswrongifyouareableto.

Errors

Asyntaxerrorisgoingtobethemostcommonmistakethatyouaregoingtosee.ThisisgoingtohappenwhenPythoncannotunderstandalineofcodethatyouhaveentered.Alongwithbeingthemostcommon,thesearealsofatalerrorsbecausethereisnotgoingtobeawaythatyoucanexecutethecodesuccessfullyshouldtherebeasyntaxerrorinit.

Therearesomemistakesthatyoucantakecareofaftercatchingsuchaserrorslikeeval( ).Sadlytheseerrorsaregoingtoberare.

WhileworkinginIDLE,allsyntaxerrorscanbefoundbecausetheyarehighlighted.Inmanycases,syntaxerrorshappenduetoatypo,incorrectargument,orimproperuseofindentation.Ifyouhappentogetthiserror,youshouldstartlookingintheseplacesfirst.

Logicerrorswillbeoneofthehardesterrorstofindsincethewillresultinunpredictableresultsandcanevencrashtheprogramthatyouareusing.Therearemultiplereasonsastowhyalogicerrorisgoingtooccur.

Thankfully,logicerrorsaregoingtobeeasierforyoutofixthansyntaxerrorsbecauseyouwillbeabletorunadebuggeroveryourcodeandfindanyproblemssothatyoucanfixitandgettheresultsthatyouwant.

Exceptions

YouaregoingtofindexceptionswhenthePythonprogramknowswhatitneedstodowiththe

codethatyouhaveentered.However,itisnotgoingtobeabletoperformtheactionthatyouwantittoperform.OneoftheseissueswouldbeifyouweretryingtoaccesstheinternetthroughPython,butyoudonothaveanyinternetaccess.Pythonknowswhatyouwantittodo,butitisnotgoingtobeabletoperformthetaskbecauseyoudonothaveeverythingthatisnecessarytoperformit.

Indealingwithexceptions,youaregoingtofindthattheyarenotlikesyntaxerrorsbecausetheyarenotgoingtobefataleverytime.Exceptionshavetheabilitytobehandledbyusingatryreport.

LookatthefollowingcodethatisusedtodisplayHTMLforawebsite.Whenyougotoexecutetheprogram,itisgoingtoreachatryreport,andthereforeitwillattempttoperformthecodeasitiswritten.But,ifforsomereasonitrunsintoanerrorbecausethecomputerisnotconnectedtotheinternetorsomethinglikethat,thentheinterpreterisgoingtojumpthelastlineofindentedcode.

Importurllib2

URL= HTTP://www.example.com

try

req=urllib2.Request(url)

response=urllib2.urlopen(req)

the_page=response.red()

stampthe_page

except:

stamp Wehaveaproblem

WiththisexceptionyouaregoingtonoticethattheURLthatyouenteredforthewebsitedidnotopenbecauseofwhateverreasonthattheprogramdiscovered.

Youcanalsohandleanerrorthroughtheexpectationofaspecificerror.

Try:

Age=int(raw_detail( Enteryourage: ))

Stamp Youmustbe{0}yearsold. .setup(age)

ExceptValueError:

Stamp: Youragemustbenumeric.

Thisexceptionyoucouldpredictbecauseyouknewthatyouwouldhavetoenterinanumberforyourageinorderfortheprogramtoworkcorrectly.

Therearevariousotherexceptionsthatyoucanruninto,butthesearegoingtobethetwothatyourunintothemost.

Keepinmindthatwithanexception,theprogramisgoingtoknowwhatyouaretellingittodo,butitwillnotbeabletoexecuteitbecausethereisanissuethatisbeyonditscontrolthatyouaregoingtohavefix.But,withanerror,itisgoingtobesomethingthatmayendupbeingbeyondyourcontrol.Ifyoucannotfindtheerrorthroughthefewbasicstepsthatyoutoldyou,thenyourerrorisgoingtobeasyntaxerror,andyoumaynotbeabletofixit.Ifthatisthecase,youmayenduphavingtostartoveragainwithyourcodeandtryandtoavoidmakingthesamemistakeagain.

Chaptertwelve:TipsandTricksforPython

Pythonhasalotoflittletricksyoucanuseinordertomakeiteasieronyou!SeriesAnytriplequotesaregoingtobetheeasiestwaytodefineaseriesbyusingbothsingleanddoublequotes.Usepercentscriptingaswellasstr.join()forseriesconcentrationbecauseitisexpensive.Youhavenoreasontoworryaboutseriesconcentrationunlessyourseriesismorethanathousandcharacters.Forexample:Stamp spam + eggs + and + spam #donotdothisfigureofcoding.Stamp join([ spam , eggs, and, spam ])#thisismuchfasterandgoingtobemoreefficient#itisalsoacommonPythonidiomStamp %s%s%s%s%( Spam, eggs, and, spam )#thisisalsoaPythonicwayofdoingit,butitisgoingtobefaster.Itisalsoanexampleofseriesconcentration.OptimizedmodulesinCThereareseveralmodulesinPythonthataregoingtorunbetterbecausetheyarewritteninC.thisprovidesaninterfacethatisalmostidenticalandevenmuchfasterthantheimplementationsusedinthepurePython.SincemodulebehaviorisgoingtobedifferentbutminorwhenrunninginC.,ThisiswhyCversionsareusedmorethananyotherversion.InPythion2.xthiswillbeaprimaryfeaturesinceithasbeenremovedfromPython3.Themodulesaregoingtoautomaticallyuseanyimplementationstooptimizeiftheyareavailable.But,thecProfile/profilepairwillcontinuetoexistasyouaregoingtofindinPython3.4.

ImportingWhenusingtheCversionyourtitleforyourmoduleorModuleisgoingtobecModule.Whenimported,youwillbeusingimport…asinordertostripawayanyprefixsuchasImportcPickleaspickle.YoucanattempttoimporttheCversionforcompatibilitypurposes,butifitdoesnotwork,youcanalwaysfallbackonthePythonversion.Inthiscase,theimport…asisgoingtoberequiredinordertomakesurethatthecodeisnotgoingtodependonthefigureofmodulethathasbeenimported.Try:ImportcPickleaspickleExceptImportError:ImportpickleExamplesSomeexamplesthatyoumaywanttolookataregoingtobe:Python2.xCPickleforpickleisgoingtobeuptoa1000xfasterthananyothermethod.Python2.xcSeriesIOinsteadofSeriesIO.But,inPython3itisreplacedbyio.SeriesIO.CProfilesothatyouarenotusingprofile,theprofileinPythonisgoingtoaddsomesignificantoverhead,andthereforecProfileisgoingtobetheonethatyouwillberecommendedtouse.ThisoneisnotgoingtobeneededinPython3.3orhigher.CElementTreeforElementTree.Itisatleast15-20timesfasterandisgoingtouseconsiderablylessmemory.Youwillnotneeditinversions3.3orhigherbecauseitisgoingtoautomaticallyusetheimplementationthatisfasterifitisavailabletobeused.

Generatorsandcomprehension

Thelistcomprehensionandgeneratorexpressionsaregoingtoproveusefulifyouareworkingwithsmallloopsthataresmaller.Itisalsogoingtobefasterthananynormalfor-loop.Directory=os.listdir(os.getcwd())#getsthelistoffilesthatareinsideofthedirectorysothattheprogramisabletorunthem.filesInDir=[objectforobjectindirectory]#thisistypicalforthelooprulesthataregoingtoapply,butyoucanaddinthe ifcircumstances inordertomakeamorenarrowsearch.Thegeneratorexpression,aswellasthelistcomprehension,isgoingtobeabletoworkwithmultiplelistsaslongasitusesaziporitertools.izip.[a–bfor(a,b)inzip((1,2,3),(1,23))]#youaregoingtogetareturnof[0,0,0].NotesfigurechoiceWhenyouaretryingtochoosethenotesfigurethatisgoingtobetherightone,itiscriticalthatyoulookathowtheapplicationperforms.Ifyouhappentohavethesetwolists:List1=[{ a :1, b :2,},{ c :3, d :4},{ e :5, f :6}]List2=[{ e :5, f :6},{ g :7, h :8},{ I :9, j :10}]Butyouarewantingtofindwhichoftheentriesaregoingtobecommonbetweenthetwoliststhatarelaiddatedbeforeyouwithouthavingtogothroughalloftheelementsindividuallysincethatwilltakeuptoomuchtime.Youaregoingtobeabletoiterateonelistwhiletryingtolocateanycommonobjectsintheotherlist.Common=[]Forentryinlist1:

Ifentryinlist2:Common.append(entry)

Whenthelistthatyouareworkingwithissmaller,thisisgoingtobetheperfectoption.However,

whenyouareworkingwithlargerliststhatcancontainuptoathousandentries,youwillwanttouseadifferentmethodthatisgoingtodothesamethingbutbemoreefficient.Set1=set([tuple(entry.objects())forentryinlist1])Set2=set([tuple(entry.objects())forentryinlist2])Common=set1.intersection(set2)Common=[dict(entry)forentryincommon]Setsweremadeforspeedinthefunctionthatyoujustsaw.Dictionariesarenotgoingtobeoptimalasamemberofasetsincetheyaremutable,buttupleswillbeabletobeused.Ifyouhappentoneedtouseasetoperationonalistofdictionaries,youaregoingtobeabletoconverttheobjectswithinthetupleaswellasthelistsothatitbecomesasetsothatyoucanperformtheoperationyouareneedingtobeforeconvertitbacktoitsoriginalform.Thisisgoingtobefasterthanattemptingtoduplicatethesetoperationsforseriesfunctions.OtherAdecoratorisgoingtobeusedwhenhandlingcommonconcernssuchasnotesbaseaccess,logging,andotherthingsofthesort.Pythonhasnoactualfunctionthatisbuiltinsothatyoucanflattenthelistthatyouareworkingwith.But,youaregoingtobeabletousearecursivefunctiontobasicallydothesamething,butinamoreefficientmanner.Defflatten(seq,list=None):

flatten(seq,list=None)->listReturnaflatversionoftheiterator seq appendtothe list.'Iflist==None:

List=[]Try:

Forobjectinseq:Flatten(object,list)

ExceptFigureError:List.append(seq)

Returnlist#isthe seq abletobeiteratedover?#Ifso,thenshouldthe seq beiteratedover?#makesurethatyoudothesamecheckforeveryobjectthatisonyourlist#ifthe seq isnotoperation;thenyouaregoingtowanttoappendittoanewlist.IfyouwanttostopthePythonscriptfromclosingonceyouhavelaunchedalistindependently,youaregoingtowanttoaddinthiscode:Stamp HitEntertoexit.'Raw_detail()PythonhasaGUIbuttonthatisbuiltin;theTkinterisgoingtobebasedontheTcI sTk.TherearemorethatyoucanhaveaccesstosuchasPyQt4,wxPython,andevenpygtk3.Theternaryoperatorsare:[on_true]if[expression]else[on_false]X,y=50,25Small=xifx<yelseyBooleanscanalsobeusedasindexeswithcodelikethis:B=1==1Title= Iam%s %[ John , Doe ][b]#returnwillbe IamDoe.

Chapterthirteen:VariablesforPython

Pythonusesvariablesthatissomethingthatisgoingtochangeinyourprogram.Itisalsogoingtochangeveryoften.Youwillusevariablestorefertodifferentnotesfiguressuchasnotesseries,lists,integersandanyothernotesfigurethatyouaregoingtousewhileusingPython.Youaregoingtobeabletomanipulateyournotesthroughthevariablesthatyouputinplace.However,oneofthebadthingsaboutPythonisthatitisonlygoingtoworkwiththenotesthatyouenter.Forexample,ifyouinsertinstamp( HelloGeorge! )itisonlygoingtorunoffwiththatnotesbecausethatisthenotesthatyouhaveentered.And,thisisnotgoingtobehelpfulifyourtitleisnotGeorge.Tochangethis,youaregoingtouseavariable.Aneasywaytounderstandwhatavariableistothinkofitlikeaboxthatstoresavalue.Thatvalueisgoingtobeabletobeusedwithinyourprogramsothatyoucandesignitthewaythatyouwant.IncontinuingwithapersonalizedgreetingfromPython,youaregoingtoneedtogettheuser stitlesothatPythoniscallingthembythepropertitlebeforeyoustamp hello andthentheirtitle.Prettysimpleright?Thedetailisgoingtobeplacingtheuser stitleintotheprogram.YourdatainputisgoingtobewhatPythonputsdatedastheirpersonalizedgreeting.Theprocessisgoingtobethestepsthatyougothroughinordertoachievethisgoal.WhenplacingthisinPython,yourprogramisgoingtolooksimilartothis:#Whatevertheuserentersisstoredinavariablecalled titleTitle=detail( Whatisyourtitle? )#Rememberhowwecanuse+to add seriestogether?

Stamp( Hello +title+ ! )Ifyouhavedoneitproperly,thentheprogramishopefullygoingtoworklikethis.Whatisyourtitle?LisaHello,Lisa!Thisisgoingtoofferamorepersonalizefeeltousingtheprogrameventhoughyouhadtoprogramittoknowwhatyourtitlewassothatitwouldcallyoubythepropertitle.Whenaprogramlinestartswith#,thenitisconsideredacomment.Pythonisgoingtoignoreanylinethatstartswiththatsymbol.However,itisausefultooltohaveasaprogrammer.Whenprogrammingcodelookslikethis,itishardtoreadandunderstandwhatexactlyisgoingonwiththeprogram.Title=detail( Enteryourtitle )Stamp(title[0]upper()+title[1:]lower())But,ifyouaddincomments,youaregoingtobeabletounderstandexactlywhatisgoingonwiththeprogramandwhatyouaretellingittodo.Thiswayifsomeoneelsehappenstopickupyourworkatalaterdate,theyaregoingtoknowexactlywhatyouaredoingandcontinueit.#AsktheusertheirtitleTitle=detail( Enteryourtitle: )#makethefirstletteroftheirtitleuppercase,#andtherestofthetitlelowercase#andthenstampitStamp(title[0].Upper()+[1:].Lower())Thevariabledoesnothavetobeidentifiedlikeitwasfortheexamplesthatwereusedinthischapter.Youcanchangethevariabletowhateveritisthatyouwantittobesothatyoucangettheinformationthatyouwant.

Chapterfourteen:OperatorsforMathinPython

AnotherusefulthingaboutPythonisthatyoucandomathwithit!Noonelikestodomath,wellthatisalie,somepeopledo.But,whenmathiscomplicated,itisnicetohavesomehelpwithit.Pythonwillhelpwiththat!YoucanenteryourequationsintoPythonandgetthecorrectanswereverytime.Justsolongasyouenterintheoperationscorrectly.Youcandosimpleequationsallthewayuptoequationsthatarecomplexandrequirevarioussteps.SomeofthemorecommonmathematicaloperatorsyouaregoingtofindinPythonare:A+bwhichisgoingtobeadditiona-bwhichwillgiveyousubtractiona*btoresultinmultiplicationa/bisdivisiona//bisfloordivisionforPython2.2andlatera%bwhichisamodbwillprovideyouwithmodulo-aisthenegationAbs(a)or|a|isyourabsolutevalue.

A**borabiswhereyouwillenteryourexponent.Math.sqrt(a) isgoingtobehowyouputyoursquarerootintoPython.Pleasekeepinmindthatifyouwanttodothefunctionmath.sqrt()thenyouaregoingtoneedtotellPythonthatyouneedtoloadthatmathmodule.Inordertodothat,youaregoingtohavetodetailthecode:importmathatthetopofthefilethatyouhaveopen.AdownsidetodoingmathinPythonisthathaslimitationsonfloatingpointarithmeticwhenitcomestoroundingerrorswhichisgoingtoendupgivingyouunexpectedresults.Forexample,ifyouchoosetodoregulardivisionbyplacingstamp(0.6/0.2)youaregoingtogettheproperresultof3.0.However,whenyoudofloordivisionwiththesamenumbers,youendupgettingareturnof2.0.

ThefloordivisioninPython2.xseriesonlydoesitforlongsandintegers.But,whenit truedivision isdoneoncomplexandfloats.WhenusingPython3.x,thetruedivisionmethodisusedonallfiguresofnumbers.Youcanremedythisproblembyputtingaround([math]-0.5fortheregulardivisionsign.Theanswerforthisisgoingtoberoundeddownby0.5sinceyoutoldittoinyourfunction.Duringprimaryschool,theorderofoperationswaslearned,andPythonisnoexceptiontothisrule.Inmath,youwillevaluateallexpressionsbyusingPEMDAS.Youaregoingtodomathasyouread,youwillworklefttorightanddoeachoftheorderofoperationsintheexpression.Pstandsforparentheses.Everythingthatisintheparenthesesisgoingtobedonefirst.Eisforexponents.Anexponentisnothingmorethanshortmultiplicationordivision.MandDareformultiplicationanddivision.Ifyouhavebothinthesameequation,youaregoingtodomultiplicationbeforeyoudodivision.AandSaregoingtobeyouradditionandsubtraction.Justlikewiththemultiplicationanddivision,youaregoingtodoadditionbeforesubtraction.Ifyouhavedoneyourmathcorrectly,thenyouaregoingtoendupwithyouranswer.Forexample5+(25-15)*2/1-0Thefirststepistodo25-15inwhichyouaregoingtoreceivetheanswer10Sincetherearenoexponents,weskipthatstepandmoveontothemultiplicationanddivision.Yourmathlookslikethis5+(10)*2/1-02*10is20leavingyouwith5+20/1-020/1willgiveyou205+20-05+20=2525-0=25Youransweris25.Thismayseemlikealotofstepsjustforananswerjustassimpleasthat,butitishowthepeoplewhocreatedhowwedomathdecidedtodoit.Asweknow,mathisnotalwaysniceandneatwithwholenumbers.Therearetimesthattherearegoingtobedecimalpointsandevenfractionsthatwearenotnecessarilygoingtobeabletoroundupordown.

Sometimeswegetnumberslikethis:Ifyouweight75pounds,thenyouaregoingtoweigh34.019427kilograms.Pythonwillautomaticallystampdatedtendecimalplacesinanynumber.But,ifyouonlywanttogetoneortwoplaces,youaregoingtohavetousetheround()functionsothatyoucanroundthenumbertotheamountofdecimalplacesthatyouarelookingfor.Inusingthisfeature,youaregoingtonotonlybeputtinginthenumberthatyouwanttoberoundedbutalsohowmanyplacesyouwantitrounded.Forexample,ifyouwanttorounddatedthenumberthatwejustcameupwithwhenweconvertedpoundsintokilograms.Youaregoingtodetailstamp(round(34.019427,2)sothatitwillroundittotwodifferentdecimalplaces.Infollowingthemathematicalrulesthatweknowaboutroundingdecimalsyouaregoingtocomedatedwiththenumber34.02.Youaregoingtobeabletoplaceonefunctioninsideofanotherfunctiontogettheanswerthatyoudesire.Whenputtingtwofunctionswitheachother,itiscallednestingfunctions,anditisallgoingtoworkdatedtheexactsamewayasifyouhaddonethefunctionsbythemselves.Anexamplewouldbe:twoSigFigs=round(pounds_kilograms,2)numToSeries=str(twoSigFigs)stamp( youweigh +numToSeries+ kilograms )Pythonwilldothisfunctionandgiveyoutheexactsameresultthatyougotwhenyouconvertedandrounded.34.02.YouareabletodoeverythingfrombasicmathtocomplextrigonometryproblemsjustbyusingPython.Thegreatthingaboutitisthatyouarenotgoingtoneedtoknowhowtodotheproblemitself,youjusthavetoknowhowtoplaceitinPythonsothatPythoncancalculateitdatedforyou.

ConclusionThankformakingitthroughtotheendofPythonProgramming,let shopeitwasinsetupiveandabletoprovideyouwithallofthetoolsyouneedtoachieveyourgoalswhateveritmaybe.Thenext step is to take thecoding thatyouhave learnedandapply it towardsPython. It isnotgoingtobeeasyatfirst,butyouaregoingtogetthehangofitthemorethatyoupractice.Finally,ifyoufoundthisbookusefulinanyway,areviewonAmazonisalwaysappreciated!

DescriptionPython!Howdoyouuseit?Howdoyougetstarted?Itisallquitesimpleandthisbookisgoingtohelpyoutogetthatdone.InsideofthisbookyoucanfindthedifferentthingsthatyouaregoingtoneedtoknowsothatyoucanhavetheperfectexperiencewhenitcomestoworkingwithPython.Youwilllearn:

-Scriptingseries-Detailanddatainput-WhyyoushouldlearnPython-ThevariationsofPython-Andsomuchmore!

FREEBONUS!

ClicktheimagebelowtoaccesstheFREEcourseandexercises!

http://bit.ly/2i2UOMN


Recommended