PYTHON
EasyPythonProgrammingforBeginnersYourStep-By-StepGuidetoLearningPython
Programming
FelixAlvaro
Acknowledgments
Firstly,IwanttothankGodforgivingmetheknowledgeandinspirationtoputthisinformativebooktogether.Ialsowanttothankmyparents,mybrothersandmypartnerSilviafortheirsupport.
TableofContents
ChapterOne:WhatisPython?
-HistoryofPython
-WhatisPythonmainlyusedfor
-WhatarethebenefitsofusingPython
-WhatmakesPythonbetterthanotherlanguages
ChapterTwo:InstallingPython
-Howitworkswithdifferentcomputersystems
-Mac
-Windows
-Linux
-Step-by-stepinstallation
ChapterThree:IntroductiontoProgrammingwithPython
-Creatingyourfirstprogram
-Writingyourfirstcommand
ChapterFour:UsingPythonasaCalculator
-Numbers
-Variables
-StringValues
-StringMethods
-Lists
ChapterFive:ControlFlowTools
-IfStatement
-IfElseStatement
-ElifStatement
ChapterSix:Loops
-ForLoops
-WhileLoops
-WhileTrueLoops
ChapterSeven:DefiningFunctions
-Functionparameters
-Passstatement
-Defaultparametersforarguments
-Keywordarguments
BeforeYouGo+FinalWords
-RecapandFinalwords
-Checkoutmyotherbooks
-Freebonusvideotrainingcourse
©Copyright2015byD.A.Alvaro-Allrightsreserved.
Thisdocumentisgearedtowardsprovidingexactandreliableinformationinregardstothetopicandissuecovered.
Itisnotlegaltoreproduce,duplicate,ortransmitanypartofthisdocumentineitherelectronicmeansorinprintedformat.Recordingofthispublicationisstrictlyprohibited.
Theinformationprovidedhereinisstatedtobetruthfulandconsistent.Undernocircumstanceswillanylegalresponsibilityorblamebeheldagainstthepublisherforanyreparation,damages,ormonetarylossduetotheinformationherein,eitherdirectlyorindirectly.
Respectiveauthorownsallcopyrightsnotheldbythepublisher.
Theinformationhereinisofferedforinformationalpurposessolely,andisuniversalasso.Thepresentationoftheinformationiswithoutcontractoranytypeofguaranteeassurance.
Thetrademarksthatareusedarewithoutanyconsent,andthepublicationofthetrademarkiswithoutpermissionorbackingbythetrademarkowner.Alltrademarksandbrandswithinthisbookareforclarifyingpurposesonlyandaretheownedbytheownersthemselves,notaffiliatedwiththisdocument.
Introduction
Congratulationsondownloadingthisguide!YouareoneofafewpeoplethattaketheirlearningseriouslyandactuallymakethefirststeptolearningsuchanamazingprogramminglanguagesuchasPython.Bydownloadingthisbook,youwillnotonlybeabletolearnthebasicsofcodinglanguage,butyouwillalsoexcelandhavecompletecontrolonthistechnology.
Youhavetobeawarethatyou’reabouttodosomethingyoucouldn’tdobefore,whetheritisoutoffear,orperhapsoutofdoubtinyourownabilities.It’struethatCodingmightsoundcomplexandextremelycomplicatedatfirstsight.Andthereisnodenyingthatsomepeopledon’tevendaretogiveitachance.Butnow,thatyouhavethisstep-by-stepguideline,noneofthatactuallymattersanymore.Forwhatyouareabouttolearn,followingthestepsinthisbook,isabsolutelyincredible.Thosestepsareinfacteasy,simpleandstraighttothepoint.Youdonotneedtohaveanyspecificbackgroundwhatsoeverinordertograspthem.AlltheanswerstoyourfuturequestionsusingPythonaresimplyhere,welldetailedandincrediblyaccurate.
Ifyou’restartingfromscratch,everytimeyouwillwriteacode,you’regoingtobemesmerized.Itwillkeeppushingyouconstantlytodiveevenfurtherintoit.Andbelieveitornot,onlythenwillyourealizethatyouareabletodomore,tomanipulatethecodingandtotransformitasyouplease.Thepointis,youwillseeyourselfimprovingasthistrainingprogresses.Allyouwillhavetodoistoalwaystakethenextstepandyourprogresswillastonishyou.Youwillbeamazedhoweasyandreachablethisartoftechnologyis!WhatyoucertainlymustknowisthatwhenitcomestoPythonthereisnoexperiencerequired.Soifyouhaveneverwrotealineofcode,thisistheperfectplacetostart.Whatmakesthisbookcompletelydifferentfromtheotherguidesisthatitaccompaniesyouthrougheverystepyoutakefromtheveryfirststartandguidesyougentlythroughoutallthebasics.
Asweallknow,programmingisnowoneofthemostpowerfultoolstosolvedifferentkindsofproblems.Allfieldsarenowinescapablytouchedbythistechnology.Youhaveasmallbusinessandyou’recurioustoknowifthisbusinessofyoursisthrivingaccordingtosocialmedia?Youcangooutthereandwriteyourowncodetocollecttweets,sharesandlikes.Youneedtobuyahouse,acar,orevenayachtandyoucan’tfigureouthowtohandleyourmoney?Pythonwouldhelpyoucalculatehowmuchyouneedtosaveforover3or5years.Youwon’tneedyourbankcounselloranymore;youwillbeyourown!It’samazingwhatonecandooncetheygetagraspofthistechnology.
Icanpromiseyouthatonceyouhavefollowedtheinstructionsincludedinthisbook
andcarefullypracticedeverybitofthem,codingwon’trepresentaproblemforyouanymore.Itwillontheotherhandbetheembodimentofanewwonchallenge,andmostimportantly,onethatwouldmakeyourdailylifesomucheasierandincrediblyneater.
Pythonisawonderfulprogramminglanguage.Itismodern,portable,powerfulandabovealleasytolearn.Don’tjustsitthereandsurrendertoyourfearsofpossiblefuturefailures.Becausethatisunlikelytobeanoptioninyourcase.Ofcoursenot,nowthatyouhavethisbookatyourfingertips.Goaheadandgiveitashot,Ipromisethatyouwon’thavetheslightestregret.Ratherbegratefultothisamazingnewtoolatyourreach.
ChapterOne:WhatisPython?
InthischapteryouwilllearnaboutthehistoryofPython,whatitismainlyusedfor,itsbenefitsandwhatmakesitbetterthanotherlanguages.
HistoryofPythonPythonhasbecomeoneofthemostinterestingprogramminglanguagesofourtime.
ItwasconceivedbyGuidovanRossumatCWIintheNetherlandsduringthelate1980’s.Whatispeculiaraboutitscreationisthatthisrevolutionaryprogramcametolifeoutofasimple“hobby”;quotingVanRossum.Infact,thelatterintendedtostartthisprogrammingprojectwiththesolepurposeofentertainmentandkillingsometimeduringtheChristmasweekofDecember1989.
Whatismostlyamazingaboutthisstoryisthathecreateditusingsolelyhiscomputer.Hisofficewasclosed,andallhehadwasthissimplemachineandhisbrilliantmind.Thus,thefirstversionofthisprogramfirstappearedin1991,thatis25yearsago.PythonwasironicallynamedafterthefamousBritishsketchcomedyseries“MontyPython’sFlyingCircus”asthefoundingfatherwasabigfan.Duringthefollowingyear,thelanguagegotadoptedbytheteamoftheAmoebaproject,whileGuidopursueditsdevelopmentmainlyinhissparetime.
InFebruary1991,thefirstpublicversionofPython,numbered0.9.07,waspostedontheUsenetalt.sourcesforum.In1995,VanRossumcontinuedhisworkonPythonatCNRIinReston,UnitedStates,wherehereleasedseveralversionsofthesoftware.WhereasPython0.6wouldbethelastversiononGrail(anextensibleInternetbrowserwritteninPython.).
Nevertheless,itdoesnotstophere.Asamatteroffact,Pythoncontinuestoimpresswithitscontinuousdevelopmentandprogress.ThedevelopmentteammovedtoPythonBeOpen.comin2000.AndthatiswherePython2.0wasreleased.
However,itdidnotstopthere.Pythonsucceededinreleasingthenewmajorversion,Python3.0,whichwasoutinDecember2008.Soonenough,thisversionwasrapidlyfollowedbya3.1versionfixingthemistakesoftheprevious.
WhatisPythonMainlyUsedFor?Pythonisdesignedmainlytomaximizetheprogrammer’sproductivitybyproviding
high-leveltoolsandasimplesyntax.Itiswithnodoubt,anecessityforthosewhowanttogetintoprogramming.Itisconsideredagoodlanguageforbeginners,ifnotthebest.Thisisduetoitsgreatandstrongstatictypesystemthatalotofprogrammersusuallypreferoverothertypesystems.Ithelpsyouavoidmakingmistakeswhilecoding.WithItsstrictstatictypes,youareindeedlesslikelytoconfusethevariables.
Pythoncanalsobeusedforscriptingprototypesandwebprojects.Itcanaswellwritecommandlineapplications.Itisindeedoneofthefewlanguagesthatembedoneapplicationinanother.Actually,pythongetsusedondifferentwebservershandlingweb-hostingthroughoutitsnumerousmodules.Nonetheless,itservesasamediatorbetweenyouandyourcomputer,throughoutfacilitatingthecommunicationandallowingyoutogiveorders!Itcouldalsobedescribedasatranslator,whereyoucaninteractwithyourcomputerusingyourpc’sownlanguage.Basically,inotherwords;thePythonscriptyouaregoingtowritewillnotatallneedanyalterationsoradjustmentsinordertobereadbyyourcomputer.Itratheristransferredortranslateddirectlytoyourcomputertobeinstantlyunderstood.
TogivealittleglimpseathoweasythisinteractioniswhileusingPython,hereisamachinecodeusedtowriteasentenceassimpleas:(Helloworld).
Whereaswhenitcomestowritingthesamesentenceonpython,itismuchlesscomplex,asitisshowedhere:
Nowit’suptoyoutodecidewhichscriptisclearer,easierandsimpler!
Pythonisoftenusedbysystemadminstocreatetheso-calledrepetitiveorsimplymaintenancetasks.Besides,ifyouwanttocreatejavaapplicationsbycodinginPython,itnowbecameabsolutelypossible.NottomentionallPython’susers,suchasGoogle(ForwhomGuidovanRossumhasworkedfrom2005to2012),Yahoo,Microsoft,NasaandmanyotherpopularwebsitessuchasInstagram,Pinterest,YouTube,Quora,Dropbox…etc.
WhataretheBenefitsofUsingPython?
WhywouldyouusePython?It’sbecauseofwhatyouactuallycandowithcodewhilstusingit.Codinginsimplerwordsisnothingbutproblemsolving.Andwhowouldn’twantthatafterall!Whowouldn’tliketofindsolutionstoeverything?Soattheend,itcomesdowntowhatyoureallywanttodowithit.Whateverfieldyou’reenteringorworkingin,codingcanaffectandhelpyou.AndusingPythonspecificallymakesthewholeprocessaloteasierforyou.
Thankstoitsexcellentlibrary,theopensourcecodeandthevariousonlineresourcesdestinedforreferenceandassistance,yourprogrammingwillbeabsolutelyfacilitatedandmoretransparentduringtheprocess.
Oneofthemostimportantthingsyouneedtoknowisthatoverthelastyears,Pythonwasentitlednumberoneoftheintroductorylanguages.Infact,itwasintroducedinsomeofthetopschoolsintheworld,suchasStanfordandMITandmanyothermajoruniversities.Pythonbecameprincipallythelanguagetheyteach.Andthereasonisclearlyduetoitssimplicity.Youcanbuildinverycomplicatedalgorithmsanditwouldremainabsolutelyclearandreadable.
Sometimeswehavetodealwithalotofinformation,andkeepingtrackofthemallcanbequiteupsettingandsometimesevenimpossible.Let’staketheexampleofashoppinglistforinstance.Youdonotgooutshoppingholdingtenpiecesofpaperswhereyou’vewrittenoneitemoneach.Youmakealistthatincludeseverything.ThisanalogyisveryclosetowhathappenswhenusingPython;throughwritingincodes,wemakeaclearlist.Hence,yourlifebecomesmoreorganizedandalotmorecoordinated.Andasweallknow,successonlycomeswithgoodarrangements.
WhatmakesPythonbetterthanotherlanguages?
Pythonisbyfartheeasiestlanguageprogrammingtolearn,especiallywhenyouareabeginnerandthisisyourfirstexperience.Itactuallydoesn’thavemainlimitations;itisinfactverypowerful.Andthelivingprooftothat,istheexistinghundredsofsuccessstoriesinmajorcompaniesallaroundtheworldusingpython.ThebiggestadvantageofPythonisthatitiseasilyreadable.JustlikereadingEnglish.Basically,readingPythonissosimpleandclear,thatisresemblesreadingabook.Inotherwords,thePythoncodecanevenbereadbypeoplewhoarenotatallfamiliarwiththeconceptofcodinglanguage.
ThissmallexampleofPythoncoding,mightillustratetheideabetter:
ThecodingisobviouslybasedonwordsfromtheEnglishlanguage,makingitpossibleforeveryonetofathomthesubjectmatter.Aswecanclearlynoticethewords(classstudent,name,age,gender,self,f..).Termsthatwearealreadyfamiliarizedwith.
Thisadvantageofasimpleandaccessiblecodinglanguageiswhatkeepsyoumotivatedandencouragesyoutopursueyourcoding.Evenifyougetstuckonsomething
whileprogramming,solutionsareeasytofind,verysimpleandsupereasytofathom.Moreover,onceyoulearnthebasicsofcodingwithPython,youwillbeabletoapplyallthoseconceptsinalltheotherprogramminglanguages.Whetherit’sC#,JavaScript++,Perl…Etc.Actually,nomatterwhichprogramminglanguageyou’regoingtolearninthefuture,youwilldiscoverthatPython’sfundamentalsaregoingtoreappearoverandoveragainanditwillbeaneffortlesslearningforyou.
Let’scomparePythontoothercodingprograms.TakingJavaasanexample.Itisundeniablethatthelatteriseasytounderstandandthatithasmanydocumentationsandonlineforumstohandleallquestions.AlthoughthedifferencebetweenthetworesidesinthefactisthatPythoniseasiertolearnfromacodingperspective.Thus,PythonisfarlesscomplicatedthanJava.Youcanalsobuildnewsoftwareapplicationsmorequickly.Pythonapplicationsare20%to30%ofthelengthofaJavaapplication,whichmakesthecoderunfaster.
WhenitcomestoTCL,however,itisknownforbeinganapplicationextensionlanguage,andastand-aloneprogramminglanguage.Although,ithasitsweaknesseslikeeveryotherlanguagedoes.TCLisweakondatastructuresandsimilartoJava,ithasslowexecutionofcode.Nottomentionthefactthatitlacksfeaturesnecessaryforwritinglargeprograms.Ontheotherhand,Pythonisknowntoberapidwhenitcomestowritingcodeandpowerfulastowideprogramsandalgorithms.
InthischapteryoulearntaboutthehistoryofPython,whatitismainlyusedfor,itsbenefitsandwhatmakesitbetterthanotherlanguages.IntheupcomingchapteryouwilllearnhowtoinstallPythonondifferentcomputersystems.
ChapterTwo:Installingpython
InthischapteryouwilllearnhowtoinstallPythononLinux,Windows7/8/9/10andonmac.
WhatisabsolutelyamazingaboutPythonisthatitcouldbeinstalledonyourcomputernomatterwhattypeitisandoperatorysystemithas.
HereareafewstepstofollowcarefullyinordertohelpyouinstallPythoncorrectly.Findyourcomputer’stype,proceed,andhappyinstallation!
InstallingPythononLinux
OnceyourLinuxmachineison,yourinternetconnectionisworking,onlyafewstepsarenowseparatingyoufrominstallingPython.Firstthingtodoistoopengoogle.Writedownthefollowing“DownloadPython”,orsimply“Python”.
Aftertheresultsshow,clickon“DownloadPython”asitisdemonstratedinthepictureabove.
Youwillthenbedirectedtothepython’sofficialwebsite“www.python.org”.Since
youchosethedownloadoptionatfirst,bothversionsofPythonaregoingtoshowforyoutopickwhichoneyouwishtodownload.
NowscrolldownthepageandallthereleasedversionsofPythonwillshownextto
theirreleasedates.Inthiscase,youwouldwanttoclickonthelatestversion.ThatisPython3.5.0asitshowshere.
Onceopened,scrolldownthepageoncemore,andyouwouldwanttorightclickonthefile“Gzippedsourcetarball”,andthechosetheoption“copylinkaddress”.
Aftercopyingthelink,allthatisleftforyoutodonowistodownloaditonyourmachine.Waitforawhile,thetimeitgetsaccepted,andthenyouwouldwanttotypethefollowing:“tar–xvfPython-3.5.0.tgz”.Youwillneedtotestitandthenconfigureit,thiswillonlytakeafewseconds.Whenthisoperationisover,allthatisleftforyoutodoistowritedown“make”whichwillcompilethefilesonyourmachine.
Thisoperationmighttakefrom1to2minutes,soafterwaitingabit,thelaststepistowritedown“makeinstall”inordertofinallyinstallthefileonyourmachine.Andtheinstallationwillbesuccessfullycomplete.
Pythonnowiswellinstalledonyourmachineandreadyforyoutouse.
InstallingPythononWindows7/8/9/10
ThestepsIamgoingtoshowyouareextremelyeasy,simpleandmanageable.Allyouwillneednowisyourcomputer,yourinternetconnection,andyourfullattention.
Thefirststepistogotogoogleandwritedown“Python”.Waituntiltheresearchisoverandthenclickontheofficialpythonpage:“Python.org”.
Onceyouhaveopenedthepage,youwillneedtogotothedownloadbuttonsituatedinthemiddle.Putyourmouseonthatbuttonandthenchosethe“Windows”option.
Nowyoucanseevariousoptionsforinstallers.Whatwewantinthiscase,istoclickonthelinkthatsays“windowsx86-64executableinstaller”,thefifthoptionthatis.
Oncetheexecutablefileisdownloaded,youwouldwanttoopenit,andtheinstallationsetupwillstart.Althoughbeforeclickingon“installnow”,youwillhavetochecktheoptionthatsays“AddPython3.5toPATH”.Aftercheckingthisoption,clickon“Installnow”andtheinstallationwillstart.
Whentheinstallationisover,closethesetupwindow,lookforthelocationofthefileandopenit.Fouroptionsaregoingtoappear.Inordertoopentheprogram,youwillhavetoclickonthesecondoption,“IDLE(Python3.564-bit)”.AndPythonwillberunningperfectlyfine.
Yourinstallationwillbesuccessfuloncethiswindowisopened.Andcongratulations,nowyouofficiallyhavePythononyourcomputer.
InstallingPythononMac
InordertoinstallPythononyourmac,youwillfirstofallneedtoaccesstoPython’sofficialpage“www.Python.org”.Manybuttonsandoptionswillappear.Youwillthenneedtopointyourmouseatthe“Downloads”buttonandchosethe“MacOSX”Option.
TwoversionsofPythonwillappear.Thisiswhenyouwilldecidewhichonetodownload.ThelatestversioninthiscaseisPython3.5asitshowshere.
Afterthedownloadprocessisover,openthedownloadedfile,andthePython’sinstallationwindowwillshow.Clickon“continue”,andrepeatthataction,untiltheinstallbuttoncomesup.Youwillthenclickon“install”.
WaitfortheprogramtofinishitsinstallationandPythonwillthenbeaccessibleonyourmac.
Byfollowingthesesteps,youwillhaveinstalledPythononyourcomputer/mac/Linuxonceandforall.
Nowthatyouhavethiswonderfulprogramsetupandreadytobeused,itistimeyoufollowedtheInstructionsthatwillhelpyouthroughit.
InthischapteryoulearntaboutthewaystoinstallPythononvariouscomputersystemssuchas(Linus,Mac,Windows7/8/9/10).Intheupcomingchapteryouwilllearnhowtocreateyourownprogramandhowtowriteyourfirstcommand.
ChapterThree:IntroductiontoprogrammingwithPython
Inthischapteryouwilllearnhowtocreateyourfirstprogram,andhowtowriteyourfirstcommandonPython.
Creatingyourfirstprogram
AfteryouinstallPython,youneedtoknowthatitcomeswithadefaulteditorandcompiler.It’scalled“IDLE”.Ifyouareusingwindows,youcaneasilygettoit,justbypressing“IDLE”inyourstartmenuforexample,orbylookingforitintheprogram’soriginallocation.Onceyoufindit,launchit,andthiswindowwillappearimmediately.
NowthisisthePythonshell,thosethreearrows(>>>)thatappearonthescreenarecalled“Chevrons”.
IDLEisdefaulteditorthatcomeswithpython.Afteryoulaunchit,yougetastart-upscript,clickon“File”toopenanewone.ThisiswhereyouaregoingtotypeyournewPythonprogram.Thewindowiscalled“Untitled”.Itwillallowyoutoinsertyourcommandsbutitwillnotexecutetheminstantly.
YouneedtoknowthatPythonisnotacompiledoraninterpretedlanguage.Thatmeansthatyoucantypeanythingintotheshellanditwillrunimmediately.Itisadynamicallytypedwhite-space-interpretedlanguage.Youcanforexampletypedown:
Andthelineofcodewillrun.Showing:
Itdoesn’tneedanysupportingfilesoranythingofthesort.That’swhatmakesitlesscomplexthanotherlanguages.Itjustsimplyruns.Inotherwords,it’sagreatrapidprototypinglanguage.Therefore,ifyouwanttostartcoding,thengoaheadanddoit,sinceitdoesnotneedanyoverheadfromcreatingaprojectoranythingsimilar.Youcanstartimmediately.
IfyouareonMac,youcanselectIDLEfromapplications � Python3.5.
IfyouareonLinux,youcanselectIDLEfromMenu � Programming � Python3.5.
WritingYourFirstCommand
Writingyourfirstcommandisnothingbutthebeginningforyou.Onceyouacquirethisskill,youwillbeabletowriteevenmorecomplexandlongprogramsonPython.Youwilllearnhowtorunfilesandhowtosavethem.
Usingidleisinfactthefirststeptowardswritingyourfirstprogram.Ifit’snotrunningalready,thenlaunchitandthenopenanewfileundertheoptionFile,orsimplyclickonpressCtrl+N.
Youfirstcommandwillconsistinwritingsomething.Firstofall,youwillhavetowritedown“print”andtheninsertparenthesis(..).Youwillthenneedtoputquotes“..”insideofthoseparentheses.Inbetween,simplywriteyourcommand.
Forpractice,enterthiscommandintheopened“untitled”window.
Beforerunningthiscommand,youneedtosaveyourfile,otherwiseitwillbelost.Sowhatyouareaskedtodonowistogoundertheoption“File”,andselect“Savefile”.Makesureyousaveitsomewhereeasytofind,inordertoeasilyopenitnexttimeyouwillneedit.
Nowthatyourfileissaved,youareinpositiontoactuallymakeitwork!Youwillhavetoopenitandthentoclickon“Run”,select“runmodule”andyourcommandwillimmediatelybeexecuted.
Whenyougobacktotheshell,thisistheresultthatwillshowonyourscreen:
Asamatteroffact,everytimeyourunamoduleinIDLE,theshellrestartsautomatically.
Yourfirstcommandisnowaffectedandwellexecuted.Whynottrytomodifyit!
Let’smakethisrunoncemore.Althoughthistime,youwillmaketheprocessalittlequicker.Thereisashortcutusingyourkeyboardthatwillfastentheprogram’sexecution.PressF5andseetheresultsforyourself.
Congratulations,youhavewrittenyourfirstcommandandmodifieditsuccessfully.NowthatyourealizehoweasyPythonisinwritingfunctions.
Inthischapteryoulearnthowtowriteyourfirstprogramandyourfirstcommand.IntheupcomingchapteryouwilllearnhowtousePythonasacalculator.
ChapterFour:UsingPythonasaCalculator
InthischapteryouwilllearnhowtousePythonasacalculator,manipulating
numbers,variables,stringvalues,stringmethodsandlists.
Numbers
Pythonallowsyoutodo7differentbasicarithmeticoperatorssuchas;Addition(+),subtraction(-),multiplication(*),division(/),modulus(%)andyoucanalsomakeexponentialcalculations(**)andfloordivisions(//).
Firstofall,wewillmakesimpleoperationsinthenewopenedfilefromIDLE.Theprocessisverysimilartothepreviousone.Allyouhavetodoistowritedown:Print,andthenopenboththeparenthesisandquotes.Insertthemathematicaloperationthesamewayyoudidforthetext.Onlythistime,beforeclosingtheparenthesis,youwillhavetoaddacommaandrewritethesameoperationagain.
Print(“number-arithmeticoperator-number”,number-arithmeticoperator-number)
Let’stake,forinstance,randomnumberslike5and4andtrytoapplythosemathematicaloperations.
Now,afterrunningthemodule,thecalculationwillbeimmediatelyexecuted.
Youcanevendomorecomplexoperationsandinserttheminonesinglecodingline.Suchasaddition,subtraction,multiplicationanddivisionalltogether.Justlikethefollowingexample:
WecannoticethatPythonrespectedthestandardorderofoperationsforcalculations,tocomeupwithcorrectresults:
Wheneveryouareperforminganarithmeticoperation,youhavetoknowthattheorderofoperationsmatters.Thus,youneedtoknowthatincaseyouhavemultiplicationordivision,theyaregoingtobeperformedbeforedivisionorsubtraction.Thisexamplemightmakeiteasiertounderstand.
ThisoperationisverysimilartothepreviousonewewentthroughtotestPython’scalculations.Althoughwhatisdifferentaboutit,isthatweputbracesfortheadditionandsubtraction.Pythonisgoingtogiveusdifferentvalues,sincethemultiplicationisnaturallygoingtohappenfirstinthissituation.
Youcannoticethatthefirstvalue(-3)andthesecond(0)aredistinct.ThisisduetothefactthatPythonrespectsthemathematicalorderofoperations.Soyoubetterknowyourorderstoo!
Variables
Usually,whenyouwishtoremembersomethinginthefuture,beitanimportantphonenumber,ahouseaddressorananniversarydate,youwriteitdownonapieceofpaperandsaveitinyourwalletorjournals.Thatmeansthatyouwouldputthepapersomewhereyouwouldrememberlateron.Although,withPython,youwillneedvariablestokeepthatnumbersafe!Thissafeplaceisavariableyouaregoingtocreateandassociatetoyournumber.Inotherwords,youcanconsideravariableasaplaceholderforsomethingelse,orsomekindofatemporarystorageforanyvalue.
Inordertocreatevariables,youwillneedtogivethemanamefirst,andthentoassignittoavalueofyourchoosing.
So,firstofall,wearegoingtoshowyouhowtocreateaverysimplevariable.Let’s
startwith“X”whichisaverycommonnameforvariablesinPythonandeveryotherlanguage.Whatwearetodonowistoassignthisvariabletoarandomnumber,suchus“8”forexample.YouwillwriteX=8inyourprogramandpressenter.Therefore,theletterXwillhavethevalueof8.Whenyouaredoingbasicfunctionsforinstance,insteadoftyping“8”,youwillsimplywrite“X”anditwillsimultaneouslyrepresentthatnumber.
Asyoucanclearlysee,thevariableissuccessfullyrecognizedas8.
Infact,youcandomathematicaloperationsusingthisvariable.Let’stryaddition,subtractionandmultiplicationtoseewhattheresultsaregoingtobelike.
Asyoucansee,variablesareveryflexibleandeasytocreate.
Thefunpartisyettocome!Asamatteroffact,avariablecanalsocontainafunction!
Let’sillustratethisexamplewithanewvariable,wewillnameit“Y”.Thefunctiontothisvariablewillbe“IamLearningPythonreallyfast”.Inthiscaseyouwillhaveto
write:Y=print(“IamLearningPythonreallyfast!”).
Andnowlaunchit.Don’tforgettousethekeyboardshortcutF5!
Anotherveryfascinatingthingyoucandowithvariablesisthatyoucanunpackthem.
Forexample,youdon’tfeellikewritingeachvariableandassigningittoanumberorfunctioneachandeverytimeyouareworkingonaline.Thereisabettersolutiontowriteasmanyasyouwantandeachwillhaveitsownvalue.
Let’stakeforexampleouralreadychosenvariableXwithitsvalueof8,andcreateanewonethatwewillcallZ.WecangiveZthevalueofthenumber6.
Whatwearegoingtowritenowis:X,Z=(8,6).Pythonwillunpackthosevariablesandgiveeachoneitsownvalueintheorderweputtheminto.
Youcanunpackasmuchvariablesasyouwant,aslongastheirnumbercorrespondstothevaluesgiventothem.Forinstance,youcannotwriteX,Z,G,R=(8,6,2,7,9).
Sinceyouhavevariablesfornumbers,mathematicaloperationsmaybecomesomucheasierthanbefore.Ifyouhavetowritealanguagethatincludesalotofnumbersanddigits,youwillonlyhavetotypethemonceinordertodefinethevariable.Hereisalittleexampleofanadditionoperationwhereweadd(8+6)withouthavingtousethenumber8,ratheritsvariableinstead.
Youcandothesameoperationusingonlyvariables.Nowlet’sgobacktoourXandZ!Forachange,let’sapplymorethanonemathematicaloperationthistime.Inthiscase,wewilluseaddition,multiplicationsubtractionandanexponentialcalculationtomakethingsmoreexciting.
Youmightbewonderingwhywewouldusevariableswhenwecaneasilywritethenumbersandthatthiswouldspareusalotoftime.Well,youareright,thisisanabsolutewasteoftimeincaseyouronlynumbersare8and6.Although,whatyoumustknowisthatvariablesaregoingtobeveryusefulinthefuturewhenyouareworkingonalongerprogram.Especiallywhenyouignorewhatthevalueis.
Allthosecaseswehavebeenthroughareaffectedwhenyoualreadyknowwhatthevariableisgoingtobe.Although,thisisnotalwaysthecase.Youcouldbewritingaprogramforawebsite,avideogameorabusinessjobandthevariable’svalueisnon-identified.Infact,itistheuserofthisprogramwhoisgoingtoenterhisownvalue.Inthissituation,youaregoingtogivethevariableanameandkeepitinordertoallowtheusertofillinthemissingvalue.
Let’ssaywehaveavariablecalled“W”.Weignorewhatthevalueof“W”isgoingtobe.Although,wearegoingtoinsertitinourcoding.Youwillhavetowrite:
W=input(“Enternumberhereplease:“)
Soonceyoupressedenter,whateveryoutypedinyourparenthesisisgoingtocomeupandshowtotheuser,whichwillallowthemtoinserttheirownvalue.Oncethevalueisenteredintheprogram,“W”willautomaticallybeassignedtoit.Let’sseethislittleexample.
Nowyouhavelearnthowtoassignavariabletoavalue,andhowtoallowotherstodothesamethroughcreatingthevariableyourself.Moreisyettocome.
Thereis,however,awaytofigureoutwherethevalueofthatvariableislocatedinpython’smemory.Iffact,weareabletoseethevalue’semplacementthroughouttheuseoftheid(variable)function.Onceyouhavedefinedyourvariableandassignedittoyourvalue,youcanusetheid()functioninordertoreachforitspositioninyourprogram.
Let’skeepusingXasanexampleinordertoavoidanyconfusions.
Asyoucansee,thislongnumber(166132….)isinfactX’slocationinPython’smemory.
PS:Thenumbertoyourvariable’slocationisnotnecessarilythesameasthisexample.ItdependsonyourPython’smemoryasalreadymentioned.
Nowthisishowyoucanusevariables.Practiceassigningyourvariables,andusingtheinput()functionsothatuserscanputtheirownvalues.Onceyouhavemasteredthisandgotusedtoit,youarereadytolearnthenextlesson.
StringValues
Whatisastringinthefirstplace?Doyourecallourveryfirstcommand?“Firstcommand!”?
Actuallythatfunctionwasastringitself.Astringsimplyisaseriesofcharacterswrittennexttoeachother.Youcancreateastringbywritingalineandputtingitbetween
quotationmarks.Nonetheless,onesinglecharacterisconsideredastringaswell.Thesamethinggoesfornumbers,letters,punctuationandwhitespaces.Probablyanythingyouputinbetweenquotationmarks.Inotherwords,astringthatincludesseveralcharactersis,asamatteroffact,astringcomposedofotherstrings!
Sothisisourfirstwrittenstring.
print(”Firstcommand!”)
Andthisistheresultitshowedafterlaunchingit.
Firstcommand!
Infact,thereissomethingyoushouldknowaboutstrings.Youcantypedownyourcommandusingdoublequotesorsinglequotes.Bothwillgivethesameresults.Forexample,wecanrewritethisstringlikethefollowing.
print(‘Firstcommand!’)
Andtheresultwillremainunchanged.
Firstcommand!
Althoughthethingis,youcannotmixdoubleandsinglequotationmarksinoneline.Forinstance,youcannotwritethecommandassuch:
print(“Firstcommand!’)
Noticethatthefirstquoteisdoubled,whereasthesecondissingle.Pythonwillimmediatelyshowthiserrormessage.
Whicheverquotationmarksyoudecidetochoose;youhavetocommittoitinordertobeabletolaunchyourprogram.
Youwanttoincludequotationmarksinyourstring?Let’ssayyouaregoingtowriteafamousquote,andyouwanttoincludethenameofthepersonwhosaidit!Thatwon’tbeaproblem.Pythoniscleverenoughtohaveincludedthisoptionandmadeitpossible.
Sosettleonwhichtypeofquotationmarksyouaregoingtouse(double/single)andthenusetheotheroneforactualquotationsinyourstring.Lookatthisexample:
Inthisexample,weusedsinglequotestowriteourstringanddoublequotesforDr.Seuss’words.Whichgaveusthefollowingresult:
Let’stryandmakesomethingmorefunwithstrings.Weallknowwhatarailwaylookslike.WhynotdrawoneusingPythonandasimplenumber!Firstofall,wewillneedtomakeanemptystring.Ourvariable,inthiscasewouldbecalled“Railway”,anditwillbedeclaredasanemptystring.Thinkofitasanemptydrawingpaperonwhichyouare
willingtopaintthatrailway.
Aswealreadyknow,ablankspaceisconsideredastringaswell.Thatexplainswhyvariable’svalueisrecognizedasanemptyspaceafterlaunchingit.
Nowlet’sstartbyaddingourfirsttrail.Thevariable’svalueislikelytochangeifyoudefineitotherwise.Youcanforinstanceputanadditionmark(+)andtheninserttheadditionbetweenquotes.Whenyoucallforthevariable,itwillinstantlyshowyouthenewone.
Although,aftermodifyingthisvariable’svalue,itisnotpossibletogetthesameresultsincaseyoucallforitwithoutputtingtheaddition.ThisisduetothefactthatPythondoesnotstorethatvalue.
Nowlet’skeep“Drawing”ourRailwaybyaddinganewraileachtime.
Thisprocessmighttakealongtime…Nonetheless,afterdoingthesamethingforawhile,thisistheresultthatwefinallyget.
Althoughinordertomakeitshorterandstraightforwardlyaccomplished,let’smultiplythatvariableby20andseetheresults!
YouhavenowsuccessfullydrawnarailwayusingPython!
StringMethods
Inordertomakeeasymodificationstostrings,therearemultiplemethodswecanuseduringtheprocess.Suchas:.lower(),.upper(),.replace(),.split()join(),.find(“x”),andrfind(“x”)methods.Thesemethodsareveryhelpfulandeasytouseinordertomodifyyourstringsimmediately.
lower():
Thefirstmethodwearegoingtotalkaboutiscalledtheupper().Onceyouhaveenteredyourstring,thereisapossibilityyourenderalltheletterslowercasecharacters.Inthiscase,let’suseavariableinordertomakeiteasiertograsp.Let’scallit“strMethodOne”.Onceyouhavedefinedyourvariable,you’regoingtousethismethodasitshowshere:
Infact,afteryourewritethevariableagain,youwillneedtoputadot“.”afterwards,andthiswindowwillautomaticallyshow:
Onceyouhavechosenthelowercaseandput(),thecharactersyouinsertedearlierinyourvariableareallgoingtobetransformedaccordingly.
Asamatteroffact,thismethoddoesnotaffectthevalueofyourvariableinanyway.Forexample,ifyouenterprint(variable)inthiscase,youwillseethatitwouldstillhavetheuppercase.Itwillremainintact.
upper():
Thenextmethodisactuallyverysimilartothisone.Itislikeitsmirrorinaway,givingitthereversedimage.Wecallthelatter:theuppercasemethod.Thetechniquesarepracticallythesame.Although,insteadofchoosing“lower()”,wewillsimpletypedown“upper()”.
Asyoucanclearlysee,allthelettersinourvariablearetransformedintocapitalletters.
replace():
Thethirdmethodwearegoingtotalkaboutisthereplace()method.Thisoneallowsyoutoreplaceaycharacterwithanother.Whatyouwoulddoisrewritethevariable,chose“replace”,addtheparenthesisandthenwritedownthecharacteryouwouldliketoreplaceinbetweenquotes“”,putacomma,andwritethenewcharacteryouwanttoputinstead.Itgoeslikethis:
variable.replace(“charactertoreplace”,“newcharacter”)
Let’sgoforourvariable,replacetheletter“t”withtheletter“k”andseewhatwouldhappen!
Asyoucanclearlysee,theletter“t”wassuccessfullyreplacedbytheletter“k”.
split():
Thenextmethodiscalledsplit.Itisverysimple,andextremelyuseful.Itsplitseverywhitespaceitfinds,makingbywhichthecharactersclearerandmoredistinguishedtotheeye.Theoperationisquitethesame;youwriteyourvariableandyouputsplitafterthedot;.split.
Therearemanyotheroptionsincludedinthismethod.Infact,youcanchoosewhichexactsequencetosplit.Forexample,let’ssaywewanttosplitthisstringinthefirsttwoandleaveitthewayitisforthesecondpart.Youopenupyourparenthesis,putablankspacebetweenthequotes,andthenumberofthepartstosplit.
join():
Forourfifthmethod:.join(),isalittlebitdifferentfromthepreviousmethods.Thisoneconsistsmainlyinjoininglists(whichwewillclarifyafterwards)oranysequencesthatyouwantbyusingastringyouwouldprovide.Likeforexample“/”or““,“*”..etc.
Sothismethod,unliketheonesthatpreceded,wouldactuallystartbythesequenceyouwouldwanttoaddbetweenquotes.“sequencetojoin”.join(thelistyoucreated)
find(“x”):
Oursixthmethodiscalled:.find(“x”)method.Thisonehelpsyoufindtheindexlocationofthefirstoccurrenceofacharacterofyourchoiceinyourstring.Ourstringwouldbe“Thisisthefindmethod.Andwearegoingtolookforthelocationofthefirstoccurrenceoftheletter“i”.
Theresultfortheindexlocationoftheletter“i”isshownthroughtheresult2foritsoccurrence.
rfind(“x”):
Anothersimilarmethodtothisoneiscalled:.rfind(“x”).Thismethod,however,returnsthelastindexlocationofthecharacteryouhavechosen.Justlikethefollowing.
Asyoucansee,13isthenumberoftheoccurrenceofthelastlocationofthecharacter“i”.
Sothesearethemostneededmethodswhileworkingwithstrings.Theyareextremelyhelpfulandabsolutelyimportantforanyonewhowouldworkonanykindofprogram.
Lists
AlistisoneofthemostpowerfuldatastructuresinPython.Itisasequencethatincludesmanythings.Itcouldbealistofintegers,ofcharacters,letters,words,orshortly,anythingyouwouldwanttoputinit.Allyouhavetodoinordertocreatealististoputtheelementsintobrackets“[]”.Presson“altgr+(”atthesametimeforthefirstbracket“[“and“altgr+“)”forthesecondtocloseit.
Solet’screateanewvariable,andcallit“ListOne”.ListOneisgoingtoincludeintegerssuchas:1,2,3,4and5.Ourlistwouldlooklikethis:
Now,ifyouwanttocallforthefirstelementinthelist,youwouldneedtotypethefollowing:
ListOne[0].Asamatteroffact,inPython,orinanyotherlanguage,thefirstelementofalistisconsideredtobethe0thelementinsteadofthe1st.Therefore,thefirstelementinourlistwouldbetheinteger“2”,thesecondwouldbe“3”etc.
SothisishowyouwouldrefertoelementsinaPython’slist.
Now,thethingaboutlistsisthattheycouldincludeanyelementyouwishtoputinthem.Moretothat,youcouldmixcharacters,stringsandintegersandputthemthesamelist.
Forinstance,youcouldtakethevariablewecreated,andredefinesomeoftheelementsinit.Inourcase,let’stakethe3rdelementwhichwouldbe“4”andresetittobeatextofourchoice.
Sothisisour3rdelement.Inordertoinsertwhichevercharacter,stringorinteger,youwouldhavetodothesamethingwithvariables.Afterallit’saslightmodificationofanelement.Nowlet’sredefineitwiththefollowingtext“Icanmanipulatelistseasily”.
Whatisevenmoreinterestingaboutlists,isthatyoucancreatealistWithinanother!RememberthefamousE.APoe’spoem“Adreamwithinadream”?well,PythonisTHATpoeticaswell,orsoitseems!Indeed,youcanforexampleredefinethe0thelement,thatistheinteger“1”andredefineitasanewlistofyourownchoosing.Let’sresetthiselementwithalistthatwouldinclude[-1,-2,-3,-4,-5].
Theresultwouldbe:
Asyoucansee,the0thelementnowreferstothenewdatastructure,andthevariableissuccessfullyredefined.
Nowlet’ssaythatyouwanttocreateanewvariableandgiveitthesamevalueasthefirstone.Whichmeansthatbothlistsaregoingtoincludethesameelements.Ournewvariablewouldbecalled“ListTwo”.WewouldwantListTwotohavethesamevalueasListOne.
ListTwonowsharesthesamevalueasourfirstvariable.Thatleadsustothefactthatincasewechangethevalueofeitherofthevariables,wearechangingthembothatthesametime.Forinstance,ifwechangethe4thelementinListTwo,thenewredefinedvaluewouldbesimultaneouslychangedforListOne.
Thisoperation,though,isnotcopying,rathercreatingtwovariablesandgivingthemtheexactsamevalues.
However,forcopyingyouwouldneedtotakeadifferentpath.Inthiscase,let’screateathirdvariablecalled“ListThree”.Youwouldneedtowritedown:ListThree=ListOne[:]Whichmeansthatyournewvariablewouldbethecopyofthealreadydefinedonefromthebeginningtotheend.
Youcouldalsocopyalistallwithimposingyourownconditions.Forexample,let’screateanotherlistwecall“ListFour”andonlycopyelementsuptothe3rd.Meaning,thislistwillincludethevaluesofthefirstaslongasitisuptothiselementbutnotincludingit.
PS:Torefreshyourmemory,ListOnegoeslikethis:
[[-1,-2,-3,-4,-5],2,3,‘Icanmanipulatelistseasily’,[‘Iamchangingthiselement’]]
Soournewvariable;ListFourwouldincludethosevalues.
Youcannoticethatthevaluesitheldarethe0th,1stand2ndonly.Thus,ourconditionwaswellexecuted.
It’samazinghowyoucancreatevariables,definelistsandmanipulatethemusingverysimpleandeasytechniques.Alongwithcopyingthemandimposingyourownconditions.Thesetechniquesareinfactabsolutelyusefulandcancomeinhandywhilewritingyourprograms.
Congratulations,youhavesucceededcreatinglistsandmanagedmanyPythontechniques.
Embraceyourselfforthenextchapter!
InthischapteryoulearntabouthowtousePythonasacalculator,includingnumbers,variables,stringvalues,stringmethodsandlists.Intheupcomingchapteryouwilllearnaboutthecontrolflowtoolssuchastheifstatement,elifstatementandtheifelsestatement.
ChapterFive:ControlFlowTools
Inthischapteryouwilllearnhowtousetheifstatement,theelsestatementandtheelifstatement.
IfStatement
Addinglogictoyourprogramisveryusefulinwritingmorecomplexandpracticallanguage.Inthiscase,wearegoingtoshowyouhowtotypedownaverybasicformoflogiccalledtheifstatements.Theifstatementisusedinordertochecktoseeifsomethingisthecase.Ifitisso,itwillexecuteyourcommand,otherwise,itwillsimplycontinuealongandexecuteyouotherrequests.Wearegoingtoapplythismethodwhileusingoneofthemostcommonoperatorsinourexample;“>”,“<”,“=”.
Let’schoosethevariableXandassignthenumber8toit:X=6,andanothervariableY=3.Afterpresentingourvariables,wearegoingtowritedowntheifstatementandseeiftheoperationisexecutable.
Aswecansee,XisactuallygreaterthanY,therefore,ourcommandisgoingtobeexecutedcorrectlyinthiscase.
Although,ifwetryandinversethisoperation,whereweasktoseeifXislessthanY,therewon’tbeanyexecutioninthiscase.
Thecommandwasobviouslynotexecuted,sinceinourexample,thevariableXisgreaterthanY.(6<3).
Whatwearegoingtodonowistoaddanothervariable.Let’scallitZ.ThevariableZisgoingtohavethesamevalueasYassignedtoit.Thus,Z=3.Nowlet’scompareZ,XandZaltogetherandseeifourcommandisgoingtobeexecuted.
Thisoperationiscorrect,whichiswhythecommandisgoingtobeexecutedimmediately.
Thereisanotherthingyoucanalsodowiththoseoperators.Let’scheckifislessthanorequaltoX.
Knowingthatit’sthecase,afterlaunchingit,theresultisgoingtobe:
Althoughifyouwanttoseeiftwovaluesareequaltoeachother,youcannotusetheequalsignthesamewayyouareusinggreaterthanandlessthanoperators“<”or“>”intheifstatement.
Becauseinthiscase,youwilllooklikeyouarecomparingtwovariablestoeachotherZ=Y.Thus,youaregoingtoneedtoputadoubleequalsignasitfollows:Z==Y
Anotherwaytodoit,ifyouwanttocheckifitdoesnotholdthesamevalue,anotequalsignthatis,youwillhavetoputbothanexclamationmarkandanequalsign:!=
Sothosearethebasicstotheifstatement,itisindeedaverysimplestatement,andyoucanalsoaddmanythingstoit,whichwewillseeintheifelsestatement.
IfElseStatement
Theideaoftheifelsestatement,istoaddonemorestepoflogictoyourusageoftheifstatement.Sowiththisstatement,wegettodecidewhattodonextifthecommandwetypedisnotthecase.Inotherwords,theprogramwillbelaunchedautomaticallyinbothcases,whetherourstatementiscorrectornot.
Solet’susethesamevariableswedefinedearlierandseehowthiselsestatementfunctions!
Let’ssaythatwewillcheckwhetherornotX<Y(X=6/Y=3)
Ifitisthecase,theprogramwillshow“XislessthanY”,otherwise,itwillshow“XisnotlessthanY”.
Sincewealreadyknowthatthefirstconditionisnotlogical,Pythondirectlyexecutedthesecondcondition.Therefore,itshowedoursecondcommandthatis“XisnotlessthanY”.
Infact,wecanputmorethanoneconditionatthesametime,andPythonwillstillruncorrectly,executingallofourconditions.
Forinstance,wecanaddanotherconditiontoseeifxislessthan90.
Pythonexecutebothcommandswhileusingtheelsestatementatfirstandtheifconditionnext,accordingtotheconditionsweimposed.
ElifStatement
TheideaoftheElifstatementistoaddyetanotherstepoflogictoourpre-existingifandelsestatements.Normally,whileusingthelattertwostatements,youcheckonelineandhaveitrunotherwiseifitfailstorunusingtheelsestatement.Butwhatifyouwanttousemultipleifstatements?Wouldn’tbeawasteoftimetocheckeachoneonitsownandrewritethewholeprocessoveragain?ThisiswheretheElifstatementintervenes.Itallowsyoutorunmultipleconditionswhileavoidingtheusageoftheelsestatementateachstep.Let’sgobacktoourvariables:X=6/Y=3/Z=3
WewillcheckifXislessthanZ.Knowingthatit’sgoingtofail,wewillputanelsestatement.Althoughbeforeproceeding,wewilladdanothercondition,theElifconditionthatis,inordertocheckifXisgreaterthanY.Wearecertain,however,thatthesecondconditionisdefinitelygoingtorun.
Wealreadyknowthatthefirstwillnotrunsince6>3,thusXisgreaterthanZ,notlessthanit.Whereasfortheotherresults:
Thefirststatementdidnotrun,sinceit’sillogical,thesecond,however,waslaunchedsinceXisindeedgreaterthanY.Whichdidn’ttriggertheElsestatement.Incasethefirstcondition(ifstatement)andthesecond(elifstatement)bothdidn’trun,thentheelsestatementwouldbelaunchedautomatically.
Asamatteroffact,youalsohavethepossibilitytoincludemorethanoneelifstatement,forexample,let’skeepouralreadywrittenprogram,andaddanotherconditionbeforetheelsestatement:
Youmightthinkthatbothelifstatementsaregoingtorun,althoughthatwillnotbethecase:
Asyoucanclearlysee,theprogramcameupwiththesameresultasearlier.Eventhoughweallknowthat50isinfactlessthan100.Thereasonitdidnotrun,isbecauseoncethefirstelifstatementwastriggeredastrue,Pythonsimplystoppedsearchingforsomethingtorun.It’slikeitislookingforonetrueanswer,onceitgetsit,itjuststopsasking.
Inthischapteryoulearnthowtousetheifstatement,elsestatementandelifstatement.Intheupcomingchapteryouwilllearnaboutloops.
ChapterSix:ChapterSix:Loops
InthischapteryouwilllearnaboutLoops,whichincludesbothoptions;theforloop,thewhileloopandtheTrueloop.
Generally,Pythonexecutesstatementsinaspecificorder.Forinstance,inafunction,thefirststatementisexecutedfirst,followedbythesecondandthirdandsoitgoessubsequently.Although,sometimes,yourealizethatyouneedtorunthosestatementsmanytimes.Whichismainlywhatbothforandwhileloopsareusedfor.
ForLoops
Inordertobetterclarifytheforloop’sroleinwritingyourprogram,wearegoingtoillustrateitusingalist.Liketheonewehavebeenoverinthefourthchapter.Afteryoucreateyourlist,youwillhavetowrite:forthe_name_of_the_variableinname_of_the_list:
Asyoucansee,ititeratedthroughouttheentirelistinthegoodorder.
Youneedtoknowthatrespectingtheindentationisofanextremeimportancewhenitcomestoloops.
Forexample,ifweaddastringtothisloopwithouttheindentation,itwillshowas
such:
Whereas,ifyourespecttheindentation,theresultwillbecompletelydifferentfromthepreviousone.
Inthiscase,aswecanclearlysee,thatthestring“Numbersinthelist”isrepeatedbeforeeverynumber.
Nowlet’strytoapplytheforlooponadifferentsequence.Amonthpersay.Wewillchoose“month”asourdefinedstring,andwewillnameourvariable“Letter”.
Infact,thereisanotherfunctioninpythonthatcouldhelpusmakecoulduseoftheforloop.Thisfunctioniscalledtherange()function.Thisfunctiontakestwovalues:range(startvalue,endvalue):Thisfunction,combinedwiththeforloopallowsyoutoprintthenumbersfromthestartvaluetotheendvalue.Likethisexample:
Aswecansee,theforloopandrangefunctiongeneratedthelistofnumbersfrom1to10aftertheexecutionoftheprogram.Youcannoticethatthenumber11innon-existentinthelist.Thisisduetothefactthatinthatcase,itonlygoesfromthefirstnumberuptothelast.
WhileLoops
Awhileloopisusedtoperformanoperationwhileyousetyourownconditions.Let’ssetourconditionbydefiningavariablefirst.Ourvaluewillbecalled“condition”,
andthevalueassignedtoitis2.Condition=2.Wearegoingtousethewhileloopsettingtheconditionthatitadds1duringeverystepofthewayuntilitislessthan10.
Itobviouslystoppedatthenumber9since10isclearlyequalsto10andnotless.Therefore,theconditionisfulfilledusingthatloop.
WhileTrue
Bysettingaconditiontothewhileloop,itexecutedthetaskaccordingtothatcondition.Thatmeansthatitisaninfiniteloopwhichwillbreakoncetheconditionisfulfilled.Althoughifyouwanttolooptobeinfinite,thereisanotheroptiontoitthatiscalled:whileTrue():
Thiswillstartrunningthesequenceyouenteredinfinitely,itwillnotstopuntilyoubreaktheloopyourself.Sointhiscase,wearegoingtousethewhiletrueloopwiththeifstatementinordertolimitit.OurvariablewillbeX.anditsassignedvaluewillbe8.X=8.Anotherthingwecanuseisthefunction“Break”.Whichwillautomaticallybreakitoutoftheprogram.Andthefunction“continue”toproceedtheactionweaskedfor.
Clearly,theloopwasbrokenwhenXbecameequalto15,sinceourconditionstatedthatitmustbegreaterthanthatnumber.
Inthischapteryoulearnthowtousethewhileloopandtheforloopincludingtheifstatementsandconditions.
Intheupcomingchapteryouwilllearnaboutthedefiningfunctions.
ChapterSeven:Definingfunctions
Inthischapteryouwilllearnaboutfunctions,theirparameters,theirparameterdefaults,thepassstatement,thedefaultparametersforargumentsandthekeywordarguments.
FunctionParameters
Theideaofafunctionistoassignasetofcodeandpossiblyvariablesthatareknownasparameterstoasingletext.Thus,insteadofwritingyourprogrameverytimeyouwanttoexecuteit,youwilljustwritethenameofyourfunctionanditwillautomaticallyberunning.Inordertobeginwritingafunction,youneedtodefineitusingthekeyword:def(whichisashortfordefine).Doitgoeslikethis:deffunction’sname():
Inourcase,let’schoosethename(FirstFunction)!
Sonowwehavedefinedourfunctionandfilleditwithstringsandavariablecontainingotherstrings.Althoughwhenweruntheprogram,noticethatthefunctionisnotgoingtobeexecuted.
Youmustbethinkingthatwedidsomethingwrongwhilewritingthefunction.Although,thethingis,wedefinedthefunction,butwedidnotcallforitintheprogram.Soeverytimeyouwanttocallforyourfunction,youwillhavetotypeitdownintotheshellanditwillautomaticallybeexecuted.
Anotherthingyoucando,istotypeitdownonyourfileafterdefiningit,althoughitdoesnotfollowthesameorderofliningofitsowndefinitionprocess.Asitfollows:
Youcanactuallyaddmoreoptionstoyourfunction.Whatwearegoingtoshowyounowmainlyconsistsindefiningyourfunctionandaddingvariableswithinthebraces.Let’sforexampledosomeadditionandsubtractionoperations.NameourvariablesXandY,andthenproceedwiththeexecution!
Asyoucansee,thevariablestookplacewithintheorderweassignedtothem.Incaseyouwereconfusedandneededtomakesurethevariablesarecorrect,youcandefinethemoncemoreasitfollows:
Thiscouldbeveryusefulifyouaredefiningafunctionthatincludesmanyvariablesandtheyaremorecomplicatedthanjustasimple9anda3.
PassStatement
Let’ssupposethatyouhaveafunctiontodefine,butyourememberedsomethingmoreimportantandurgenttowritedownfirst,Pythonhasanoptioncalledpass.Youcandefineyour
functionandnameit,andthentypepass,writetheotherprogrammingtaskandthenyoucangobacktoitbyrewritingitagain.
Youcanusethisoptionifyou’regoingtowriteanothervariable,string,list,charactersorbasicallyanythingyoulike,andevendefininganewfunctionisgoingtoworkoutforyou.
Asyoucansee,oursecondfunctionhasbeenexecutedconveniently,andourfirstwasconsideredasanulloperation.Thiscouldhelpyouwhenyoudon’twanttoforgetdefiningafunctionevenifyoustillignorethevariablesandtheirvaluesinordertofillit.
Defaultparameters
Whiledefiningourfunction,wecanactuallyassignavaluetoourargumentsatthebeginningoftheprocess.Forexample,wecanwriteafunctionaboutsomeone’sweightandage,andalreadygiveoutoneofthosevalueinadvance.Asitfollows:
Asyoucansee,theprogramranautomaticallyafterdefiningthefirstvariableatfirst,andthesecondatlast.Thisisduetothefactthatithadadefaultvaluetoit.Youcouldusethisdefaultparameterwhenyouignorewhattheargumentisgoingtobe.
DefaultValuesForArguments
Let’ssayforexample,youareworkingonaprogramforawebsite,andyouwanttoaskwhatthegenderofthepersonis,maleorfemale.Whatyou’regoingtodoistouseafunctionalongwiththeif,andelifstatements.
Sinceweignorewhatthegenderofthatpersonisgoingtobe,wesetadefaultvalueforthatmatter.Wealsoadded“Unknown”inordertofillintheemptyspaceincasetherewasnoanswerprovided.
Whilecallingfortheprogram,wesetouroptions,ifit’samale,theywillenter“m”,ifit’safemaleitwillbe“f”,andiftheydon’ttypeanything,thegenderisgoingtobeUnknown.
Thisistheresultwegetafterlaunchingthisprogram.
KeywordArguments
Firstofall,let’sstartwritingourfunctionusingthedefaultvaluesforargumentsthat
wesawpreviouslyinordertobeabletoapplyourmodificationslateron,usingthekeywordargumentsmethod.Ourfunctionwilldifferentfromtheoneprecedingit.Wewillsimplywriteasentenceandplayonwords.
Inthisfunction,weonlyuseddefaultarguments,andtheresultafterlaunchingitisofcoursethefollowing:
However,whatwearegoingtodotothisfunctionismorethanthat.Nowwheneverwewanttopassnewparameters,Pythonisgoingtosetthemintheorderwefirstput(Subject,Verb,Noun).
Forexample,ifwewriteadifferentsentence,likethisone:
Thefunctionwecreatedearliernamed“Sentence”takesthreevariables.Andsincewearepassingthroughanotherthreestringsvariablesrightnowinoursentence(Pythonisawesome),PythonisgoingtoassigneachItemfollowingtheordersweset.Thustheresultisgoingtobe:
Althoughifyouwanttopassitinadifferentorder,whatyouwillhavetodoistousethekeywordoftheargumentyouputatthebeginningwhiledefiningyourfunction.Let’ssaywewouldliketochangetheorderlypositionsofourparameters.
Afterchangingtheorderoftheitems,theresultisthefollowing:
Inthislastchapteryoulearnthowtodefinefunctions,usefunctionparameters,passstatements,defaultvalueforargumentsandkeywordarguments.
Congratulations!Youhavenowcompletedthisstep-by-stepguideandhavegainedtremendousknowledgeonPython!
Turntonextpagetoseeaquickrecapofwhatwehavecoveredinthisbook.
Hereisaquickrecapofwhatwecoveredincaseyouneedarefresheronacertainstep:
1. YounowhaveanunderstandingofPythonandhowtouseitconveniently.2. Youlearnthowtoinstallitwithdifferentcomputersystems.3. Youlearnthowtocreateyourfirstprogramandwriteyourfirstcommand.4. YoulearnthowtousetousePythonasacalculator(numbers,variables,string
values,lists).5. Youlearnthowtousecontrolflowtools(ifstatements,ifelsestatement,elif
statement).6. Youlearnthowtomanipulateloops(forloop,whileloop,whileTrueloop).7. Youlearnthowtodefinefunctions.8. Youalsolearnthowtousepassstatements,defaultparameters,defaultparameters
forargumentsandkeywordarguments.
Turntothenextpagetogainaccesstoafreevideocourseandtoalsoseemyotherbest-sellingbookspartofthisseries!
BeforeYouGo+Bonus
Firstofall, Iwant tocongratulateyou for theeffortsyoumadewhile reading thisbook,andyourwillanddetermination in learning thisabsolutelyamazingprogramminglanguage.
NowthatyoulearntthemostimportantbasicsaboutPython.,youarereadyventureinto thewilderness of this language.Make sure you practice everything you have beentaughtinthisbook,andtofolloweachandeveryinstructioncarefullyandthoroughly.
As you can see, Python is absolutely simple and extremely easy for a codinglanguage.Youcaneffortlesslywriteanykindofprogram,anditisaguaranteedsuccess.Notonlyisitfathomableandclear,butitalsohasmanyadvantagesonsomanylevels.
Wehavebeenthroughmanychapters,decryptingeachpointandillustratingitwithexamples and images.All youhave todonow is tohave faith inyourself and towritedownmorecomplexprograms includingmorechapterseachstepof theway.Themoreyoutrainyourself,thebetteritis.
Youwill realize that youwill bemore familiarizedwithPython’s concepts,whichwill immensely improve your writing-speed and enhance your understanding of thislanguage.
Challengeyourselfandspendmore timepracticingandrepeating theexamplesweshowed you. For we all know that practice makes perfect, and perfection is at yourfingertips.
Afteracquiringthisknowledge,youshouldconsideryourselfalreadyaprogrammer.I urgeyou to learnotherprogramming languages so that youmaybe able to takeyourknowledge to thenext andbecomea top-classprogrammer andbecauseyouhavegonethrough thiscourse,youwillbeastonished to find thatyour learningother languages iseasierthanexpected,forPythonhasstrikinglypavedthewayforyou.
Ihavemorebookspartofthisprogrammingseriesthatyoucandownload.Manyofthesebooksare#1best-sellersonAmazonduetothevalueandknowledgeallmyreadersreceive.Checktheseoutbelow.
Iwouldalsoreallyappreciateyourreviewsandyourfeedback.Ifyoureallyenjoyedthisbook,thenfeelfreetoshareitsootherpeoplemayalsoprofitfromthisinformation.
Herearesomeofmyotherawesome,best-sellingbooks!
#1Best-SellerintheSetTheoryandMathematicalSetTheoriescategories!
Learn how to program with JAVASCRIPT with my step-by-step course forbeginners.Thisbookwill teach theadvancedmethodsofwebdesign,covering thevitalHTMLandCSSbasicsandteachingyouoneofthemosthigh-in-demandskillsinthewebdesignjob-market.
“JAVASCRIPT:EasyJavaScriptProgrammingForBeginners-YourStep-By-StepGuidetoLearningJavaScriptProgramming”
YouWillLearnTheFollowing:
ThehistoryofJavaScriptanditsusesThevitalbasicsofHTMLandCSSHowtousejQueryDifferentwaystorunJavaScriptLearntheSyntax
UnderstandingCommentsUsingVariablesDataTypesUsingOperatorsDesigningFlowControl,LoopsandBranchesUsingFunctionsUsingJavaScriptObjectsWorkingwithArraysAndmuchmore!
Click-Hereorvisithttp://amzn.to/1mBhUYMtoDownloadNow!
#1 Best-Seller in the Functional Analysis and Non-Profit Organizationscategories!
Learnhowtodrivetraffic,leadsandcustomerstoyourwebsitewiththisbest-sellingstep-by-stepcourse:
“SEO:EasySearchEngineOptimization,YourStep-By-StepGuidetoaSky-HighRankingandNeverEndingTraffic”
HereisaPreviewofWhatYouWillLearn:
WhatisSEOandhowitreallyworks?HowsearchenginesoperateLearnthefirststeptogetrankedTheimportanceofkeywordsandhowtodoproperkeywordresearchandanalysecompetitivenessusingfreetoolsOn-pageoptimizationTheuseofHeader,MetaandTitleTagsTrackingyoursite’sperformanceforfree!Off-pageoptimizationandtheuseofpowerfulbacklinks8strategiestogeneratehigh-qualitybacklinksandboostwebsitetrafficWhyIndexingandSitemapsarevitalHowtogenerateandsubmitsitemapsTheimportanceofhigh-qualitycontentHowtocreatehigh-quality,engaginganduniquecontentAndMuchMore!
ClickHereorVisit;http://amzn.to/21HWFWbtoDownloadNow
#1BestSellerintheWeb-DesignandComputers&Technologycategories!
Learnhowtocreateawebsiteusingaverypopularwebdesignplatform,WordPress,withthisNumber1Best-Seller.
“WORDPRESS:SimpleWordPressGuide toCreateanAttractiveWebsiteorBlogfromScratch,Step-By-Step”
YouWillGainTheFollowingSkills:
WhyyoumadetherightdecisionbychoosingWordPressandwhattheyhavetooffer
Howtochoosetherightdomainnameandhowtogetyoursiteliveonthewebwithahostserver
HowtoeasilySynchronizeyourchosenweb-addressandHostserverwithWordPress
Howtoaddatouchofyourpersonalitythroughtheuseofamazingandfreethemes!
HowtoaddpagesandastonishingcontentforyourviewerstoenjoyAddinghigh-levelfeaturestoyoursitethroughtheuseofPluginsAndmuch,muchmore!!
Click-HeretoBuyNow!Orvisitthispagehttp://amzn.to/1VHtxZi
#1Best-SellerintheBusinessInsurancecategory!
Learn how to build a profitable online business one of the most popular onlineretailersintheworld.Followthisstep-by-stepcourseandlearnhowbuildasideorevenfulltimeincomeonline.
“eBay:FindAllYouNeedToSelloneBayandBuildaProfitableBusinessfromScratch,Step-By-Step”
YouWillGainTheFollowingSkills;
WhynowisthebesttimetostartyouronlinebusinessandwhyyouneedtobesellingoneBayHowtheentireprocessworksandwhatstepsyouneedtotaketoopen-upyourownstoretherightwayHowtoknowwhichitemsaremostprofitableandwheretofindthebestsourcesforyourproductsHowtoeffectivelyBrand&PromoteyourbusinessformoreexposureandhigherrevenuesHowtocreateahigh-ranking,eye-catchingandlucrativelisting?Howtotakeyourbusinessandyourincometothenextlevelthroughautomationandoutsourcing?Andmuchmore!
Click-Hereorvisithttp://amzn.to/1R1vnCPtobuythebookNow!
NowontotheBONUS!!Aspromised,Iamgivingyoufreeaccessto5videosfrommypopularcourse“25
WebsiteTrafficMethods”!
Havingabeautifulandprofessionalwebsiteisgreat,butwhatisthepointifno-oneisvisitingit?
That’swhythiscoursehasbeencreated!
The program is going to teach you how to drive tons of targeted traffic to yourwebsite.
Someof the lessonsmaybe familiar toyoualready,but Iamcertainyouwillgetsomegoldennuggetstogiveyouthatextrapush.
To access this course, click the button below or visit this link!>>http://bit.ly/1PtpgK7
Finally,youcanalsosendmeanemailifyouhaveanyquestions,feedbackorjustwanttosayhello!(Idoreply!)Myemailaddressis;([email protected])
IthankyouonceagainandGodbless!
FelixAlvaro