python: easy python programming for beginners, your step ...index-of.co.uk/programming/python easy...

98

Upload: others

Post on 25-Sep-2020

104 views

Category:

Documents


12 download

TRANSCRIPT

Page 1: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 2: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

PYTHON

EasyPythonProgrammingforBeginnersYourStep-By-StepGuidetoLearningPython

Programming

FelixAlvaro

Page 3: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 4: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Acknowledgments

Firstly,IwanttothankGodforgivingmetheknowledgeandinspirationtoputthisinformativebooktogether.Ialsowanttothankmyparents,mybrothersandmypartnerSilviafortheirsupport.

Page 5: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 6: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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

Page 7: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

ChapterSix:Loops

-ForLoops

-WhileLoops

-WhileTrueLoops

ChapterSeven:DefiningFunctions

-Functionparameters

-Passstatement

-Defaultparametersforarguments

-Keywordarguments

BeforeYouGo+FinalWords

-RecapandFinalwords

-Checkoutmyotherbooks

-Freebonusvideotrainingcourse

Page 8: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

©Copyright2015byD.A.Alvaro-Allrightsreserved.

Thisdocumentisgearedtowardsprovidingexactandreliableinformationinregardstothetopicandissuecovered.

Itisnotlegaltoreproduce,duplicate,ortransmitanypartofthisdocumentineitherelectronicmeansorinprintedformat.Recordingofthispublicationisstrictlyprohibited.

Theinformationprovidedhereinisstatedtobetruthfulandconsistent.Undernocircumstanceswillanylegalresponsibilityorblamebeheldagainstthepublisherforanyreparation,damages,ormonetarylossduetotheinformationherein,eitherdirectlyorindirectly.

Respectiveauthorownsallcopyrightsnotheldbythepublisher.

Theinformationhereinisofferedforinformationalpurposessolely,andisuniversalasso.Thepresentationoftheinformationiswithoutcontractoranytypeofguaranteeassurance.

Thetrademarksthatareusedarewithoutanyconsent,andthepublicationofthetrademarkiswithoutpermissionorbackingbythetrademarkowner.Alltrademarksandbrandswithinthisbookareforclarifyingpurposesonlyandaretheownedbytheownersthemselves,notaffiliatedwiththisdocument.

Page 9: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 10: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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

Page 11: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

andcarefullypracticedeverybitofthem,codingwon’trepresentaproblemforyouanymore.Itwillontheotherhandbetheembodimentofanewwonchallenge,andmostimportantly,onethatwouldmakeyourdailylifesomucheasierandincrediblyneater.

Pythonisawonderfulprogramminglanguage.Itismodern,portable,powerfulandabovealleasytolearn.Don’tjustsitthereandsurrendertoyourfearsofpossiblefuturefailures.Becausethatisunlikelytobeanoptioninyourcase.Ofcoursenot,nowthatyouhavethisbookatyourfingertips.Goaheadandgiveitashot,Ipromisethatyouwon’thavetheslightestregret.Ratherbegratefultothisamazingnewtoolatyourreach.

Page 12: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 13: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 14: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 15: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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

Page 16: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 17: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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

Page 18: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 19: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 20: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 21: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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

Page 22: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

youchosethedownloadoptionatfirst,bothversionsofPythonaregoingtoshowforyoutopickwhichoneyouwishtodownload.

NowscrolldownthepageandallthereleasedversionsofPythonwillshownextto

theirreleasedates.Inthiscase,youwouldwanttoclickonthelatestversion.ThatisPython3.5.0asitshowshere.

Onceopened,scrolldownthepageoncemore,andyouwouldwanttorightclickonthefile“Gzippedsourcetarball”,andthechosetheoption“copylinkaddress”.

Page 23: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 24: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Thefirststepistogotogoogleandwritedown“Python”.Waituntiltheresearchisoverandthenclickontheofficialpythonpage:“Python.org”.

Onceyouhaveopenedthepage,youwillneedtogotothedownloadbuttonsituatedinthemiddle.Putyourmouseonthatbuttonandthenchosethe“Windows”option.

Nowyoucanseevariousoptionsforinstallers.Whatwewantinthiscase,istoclickonthelinkthatsays“windowsx86-64executableinstaller”,thefifthoptionthatis.

Page 25: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Oncetheexecutablefileisdownloaded,youwouldwanttoopenit,andtheinstallationsetupwillstart.Althoughbeforeclickingon“installnow”,youwillhavetochecktheoptionthatsays“AddPython3.5toPATH”.Aftercheckingthisoption,clickon“Installnow”andtheinstallationwillstart.

Whentheinstallationisover,closethesetupwindow,lookforthelocationofthefileandopenit.Fouroptionsaregoingtoappear.Inordertoopentheprogram,youwillhavetoclickonthesecondoption,“IDLE(Python3.564-bit)”.AndPythonwillberunningperfectlyfine.

Page 26: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Yourinstallationwillbesuccessfuloncethiswindowisopened.Andcongratulations,nowyouofficiallyhavePythononyourcomputer.

InstallingPythononMac

InordertoinstallPythononyourmac,youwillfirstofallneedtoaccesstoPython’sofficialpage“www.Python.org”.Manybuttonsandoptionswillappear.Youwillthenneedtopointyourmouseatthe“Downloads”buttonandchosethe“MacOSX”Option.

TwoversionsofPythonwillappear.Thisiswhenyouwilldecidewhichonetodownload.ThelatestversioninthiscaseisPython3.5asitshowshere.

Page 27: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Afterthedownloadprocessisover,openthedownloadedfile,andthePython’sinstallationwindowwillshow.Clickon“continue”,andrepeatthataction,untiltheinstallbuttoncomesup.Youwillthenclickon“install”.

WaitfortheprogramtofinishitsinstallationandPythonwillthenbeaccessibleonyourmac.

Byfollowingthesesteps,youwillhaveinstalledPythononyourcomputer/mac/Linuxonceandforall.

Nowthatyouhavethiswonderfulprogramsetupandreadytobeused,itistimeyoufollowedtheInstructionsthatwillhelpyouthroughit.

Page 28: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

InthischapteryoulearntaboutthewaystoinstallPythononvariouscomputersystemssuchas(Linus,Mac,Windows7/8/9/10).Intheupcomingchapteryouwilllearnhowtocreateyourownprogramandhowtowriteyourfirstcommand.

Page 29: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 30: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 31: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

ChapterThree:IntroductiontoprogrammingwithPython

Inthischapteryouwilllearnhowtocreateyourfirstprogram,andhowtowriteyourfirstcommandonPython.

Creatingyourfirstprogram

AfteryouinstallPython,youneedtoknowthatitcomeswithadefaulteditorandcompiler.It’scalled“IDLE”.Ifyouareusingwindows,youcaneasilygettoit,justbypressing“IDLE”inyourstartmenuforexample,orbylookingforitintheprogram’soriginallocation.Onceyoufindit,launchit,andthiswindowwillappearimmediately.

NowthisisthePythonshell,thosethreearrows(>>>)thatappearonthescreenarecalled“Chevrons”.

Page 32: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 33: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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:

Page 34: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Asamatteroffact,everytimeyourunamoduleinIDLE,theshellrestartsautomatically.

Yourfirstcommandisnowaffectedandwellexecuted.Whynottrytomodifyit!

Let’smakethisrunoncemore.Althoughthistime,youwillmaketheprocessalittlequicker.Thereisashortcutusingyourkeyboardthatwillfastentheprogram’sexecution.PressF5andseetheresultsforyourself.

Congratulations,youhavewrittenyourfirstcommandandmodifieditsuccessfully.NowthatyourealizehoweasyPythonisinwritingfunctions.

Inthischapteryoulearnthowtowriteyourfirstprogramandyourfirstcommand.IntheupcomingchapteryouwilllearnhowtousePythonasacalculator.

Page 35: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 36: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 37: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 38: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Youcanevendomorecomplexoperationsandinserttheminonesinglecodingline.Suchasaddition,subtraction,multiplicationanddivisionalltogether.Justlikethefollowingexample:

WecannoticethatPythonrespectedthestandardorderofoperationsforcalculations,tocomeupwithcorrectresults:

Wheneveryouareperforminganarithmeticoperation,youhavetoknowthattheorderofoperationsmatters.Thus,youneedtoknowthatincaseyouhavemultiplicationordivision,theyaregoingtobeperformedbeforedivisionorsubtraction.Thisexamplemightmakeiteasiertounderstand.

Page 39: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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

Page 40: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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

Page 41: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

write:Y=print(“IamLearningPythonreallyfast!”).

Andnowlaunchit.Don’tforgettousethekeyboardshortcutF5!

Anotherveryfascinatingthingyoucandowithvariablesisthatyoucanunpackthem.

Forexample,youdon’tfeellikewritingeachvariableandassigningittoanumberorfunctioneachandeverytimeyouareworkingonaline.Thereisabettersolutiontowriteasmanyasyouwantandeachwillhaveitsownvalue.

Let’stakeforexampleouralreadychosenvariableXwithitsvalueof8,andcreateanewonethatwewillcallZ.WecangiveZthevalueofthenumber6.

Whatwearegoingtowritenowis:X,Z=(8,6).Pythonwillunpackthosevariablesandgiveeachoneitsownvalueintheorderweputtheminto.

Page 42: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 43: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 44: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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

Page 45: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 46: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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

Page 47: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

willingtopaintthatrailway.

Aswealreadyknow,ablankspaceisconsideredastringaswell.Thatexplainswhyvariable’svalueisrecognizedasanemptyspaceafterlaunchingit.

Nowlet’sstartbyaddingourfirsttrail.Thevariable’svalueislikelytochangeifyoudefineitotherwise.Youcanforinstanceputanadditionmark(+)andtheninserttheadditionbetweenquotes.Whenyoucallforthevariable,itwillinstantlyshowyouthenewone.

Although,aftermodifyingthisvariable’svalue,itisnotpossibletogetthesameresultsincaseyoucallforitwithoutputtingtheaddition.ThisisduetothefactthatPythondoesnotstorethatvalue.

Page 48: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Nowlet’skeep“Drawing”ourRailwaybyaddinganewraileachtime.

Thisprocessmighttakealongtime…Nonetheless,afterdoingthesamethingforawhile,thisistheresultthatwefinallyget.

Page 49: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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:

Page 50: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Infact,afteryourewritethevariableagain,youwillneedtoputadot“.”afterwards,andthiswindowwillautomaticallyshow:

Onceyouhavechosenthelowercaseandput(),thecharactersyouinsertedearlierinyourvariableareallgoingtobetransformedaccordingly.

Asamatteroffact,thismethoddoesnotaffectthevalueofyourvariableinanyway.Forexample,ifyouenterprint(variable)inthiscase,youwillseethatitwouldstillhavetheuppercase.Itwillremainintact.

Page 51: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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”)

Page 52: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 53: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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

Page 54: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Theresultfortheindexlocationoftheletter“i”isshownthroughtheresult2foritsoccurrence.

rfind(“x”):

Anothersimilarmethodtothisoneiscalled:.rfind(“x”).Thismethod,however,returnsthelastindexlocationofthecharacteryouhavechosen.Justlikethefollowing.

Asyoucansee,13isthenumberoftheoccurrenceofthelastlocationofthecharacter“i”.

Sothesearethemostneededmethodswhileworkingwithstrings.Theyareextremelyhelpfulandabsolutelyimportantforanyonewhowouldworkonanykindofprogram.

Page 55: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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:

Page 56: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 57: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 58: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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:

Page 59: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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

Page 60: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 61: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 62: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Although,ifwetryandinversethisoperation,whereweasktoseeifXislessthanY,therewon’tbeanyexecutioninthiscase.

Thecommandwasobviouslynotexecuted,sinceinourexample,thevariableXisgreaterthanY.(6<3).

Whatwearegoingtodonowistoaddanothervariable.Let’scallitZ.ThevariableZisgoingtohavethesamevalueasYassignedtoit.Thus,Z=3.Nowlet’scompareZ,XandZaltogetherandseeifourcommandisgoingtobeexecuted.

Thisoperationiscorrect,whichiswhythecommandisgoingtobeexecutedimmediately.

Page 63: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Thereisanotherthingyoucanalsodowiththoseoperators.Let’scheckifislessthanorequaltoX.

Knowingthatit’sthecase,afterlaunchingit,theresultisgoingtobe:

Althoughifyouwanttoseeiftwovaluesareequaltoeachother,youcannotusetheequalsignthesamewayyouareusinggreaterthanandlessthanoperators“<”or“>”intheifstatement.

Page 64: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Becauseinthiscase,youwilllooklikeyouarecomparingtwovariablestoeachotherZ=Y.Thus,youaregoingtoneedtoputadoubleequalsignasitfollows:Z==Y

Anotherwaytodoit,ifyouwanttocheckifitdoesnotholdthesamevalue,anotequalsignthatis,youwillhavetoputbothanexclamationmarkandanequalsign:!=

Sothosearethebasicstotheifstatement,itisindeedaverysimplestatement,andyoucanalsoaddmanythingstoit,whichwewillseeintheifelsestatement.

IfElseStatement

Theideaoftheifelsestatement,istoaddonemorestepoflogictoyourusageoftheifstatement.Sowiththisstatement,wegettodecidewhattodonextifthecommandwetypedisnotthecase.Inotherwords,theprogramwillbelaunchedautomaticallyinbothcases,whetherourstatementiscorrectornot.

Page 65: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 66: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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:

Page 67: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Thefirststatementdidnotrun,sinceit’sillogical,thesecond,however,waslaunchedsinceXisindeedgreaterthanY.Whichdidn’ttriggertheElsestatement.Incasethefirstcondition(ifstatement)andthesecond(elifstatement)bothdidn’trun,thentheelsestatementwouldbelaunchedautomatically.

Asamatteroffact,youalsohavethepossibilitytoincludemorethanoneelifstatement,forexample,let’skeepouralreadywrittenprogram,andaddanotherconditionbeforetheelsestatement:

Youmightthinkthatbothelifstatementsaregoingtorun,althoughthatwillnotbethecase:

Page 68: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Asyoucanclearlysee,theprogramcameupwiththesameresultasearlier.Eventhoughweallknowthat50isinfactlessthan100.Thereasonitdidnotrun,isbecauseoncethefirstelifstatementwastriggeredastrue,Pythonsimplystoppedsearchingforsomethingtorun.It’slikeitislookingforonetrueanswer,onceitgetsit,itjuststopsasking.

Inthischapteryoulearnthowtousetheifstatement,elsestatementandelifstatement.Intheupcomingchapteryouwilllearnaboutloops.

Page 69: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 70: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 71: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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

Page 72: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

such:

Whereas,ifyourespecttheindentation,theresultwillbecompletelydifferentfromthepreviousone.

Inthiscase,aswecanclearlysee,thatthestring“Numbersinthelist”isrepeatedbeforeeverynumber.

Nowlet’strytoapplytheforlooponadifferentsequence.Amonthpersay.Wewillchoose“month”asourdefinedstring,andwewillnameourvariable“Letter”.

Page 73: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Infact,thereisanotherfunctioninpythonthatcouldhelpusmakecoulduseoftheforloop.Thisfunctioniscalledtherange()function.Thisfunctiontakestwovalues:range(startvalue,endvalue):Thisfunction,combinedwiththeforloopallowsyoutoprintthenumbersfromthestartvaluetotheendvalue.Likethisexample:

Aswecansee,theforloopandrangefunctiongeneratedthelistofnumbersfrom1to10aftertheexecutionoftheprogram.Youcannoticethatthenumber11innon-existentinthelist.Thisisduetothefactthatinthatcase,itonlygoesfromthefirstnumberuptothelast.

WhileLoops

Awhileloopisusedtoperformanoperationwhileyousetyourownconditions.Let’ssetourconditionbydefiningavariablefirst.Ourvaluewillbecalled“condition”,

Page 74: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 75: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Clearly,theloopwasbrokenwhenXbecameequalto15,sinceourconditionstatedthatitmustbegreaterthanthatnumber.

Inthischapteryoulearnthowtousethewhileloopandtheforloopincludingtheifstatementsandconditions.

Intheupcomingchapteryouwilllearnaboutthedefiningfunctions.

Page 76: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 77: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 78: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 79: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Youmustbethinkingthatwedidsomethingwrongwhilewritingthefunction.Although,thethingis,wedefinedthefunction,butwedidnotcallforitintheprogram.Soeverytimeyouwanttocallforyourfunction,youwillhavetotypeitdownintotheshellanditwillautomaticallybeexecuted.

Anotherthingyoucando,istotypeitdownonyourfileafterdefiningit,althoughitdoesnotfollowthesameorderofliningofitsowndefinitionprocess.Asitfollows:

Page 80: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Youcanactuallyaddmoreoptionstoyourfunction.Whatwearegoingtoshowyounowmainlyconsistsindefiningyourfunctionandaddingvariableswithinthebraces.Let’sforexampledosomeadditionandsubtractionoperations.NameourvariablesXandY,andthenproceedwiththeexecution!

Asyoucansee,thevariablestookplacewithintheorderweassignedtothem.Incaseyouwereconfusedandneededtomakesurethevariablesarecorrect,youcandefinethemoncemoreasitfollows:

Page 81: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Thiscouldbeveryusefulifyouaredefiningafunctionthatincludesmanyvariablesandtheyaremorecomplicatedthanjustasimple9anda3.

PassStatement

Let’ssupposethatyouhaveafunctiontodefine,butyourememberedsomethingmoreimportantandurgenttowritedownfirst,Pythonhasanoptioncalledpass.Youcandefineyour

functionandnameit,andthentypepass,writetheotherprogrammingtaskandthenyoucangobacktoitbyrewritingitagain.

Youcanusethisoptionifyou’regoingtowriteanothervariable,string,list,charactersorbasicallyanythingyoulike,andevendefininganewfunctionisgoingtoworkoutforyou.

Page 82: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Asyoucansee,oursecondfunctionhasbeenexecutedconveniently,andourfirstwasconsideredasanulloperation.Thiscouldhelpyouwhenyoudon’twanttoforgetdefiningafunctionevenifyoustillignorethevariablesandtheirvaluesinordertofillit.

Page 83: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Defaultparameters

Whiledefiningourfunction,wecanactuallyassignavaluetoourargumentsatthebeginningoftheprocess.Forexample,wecanwriteafunctionaboutsomeone’sweightandage,andalreadygiveoutoneofthosevalueinadvance.Asitfollows:

Asyoucansee,theprogramranautomaticallyafterdefiningthefirstvariableatfirst,andthesecondatlast.Thisisduetothefactthatithadadefaultvaluetoit.Youcouldusethisdefaultparameterwhenyouignorewhattheargumentisgoingtobe.

DefaultValuesForArguments

Let’ssayforexample,youareworkingonaprogramforawebsite,andyouwanttoaskwhatthegenderofthepersonis,maleorfemale.Whatyou’regoingtodoistouseafunctionalongwiththeif,andelifstatements.

Page 84: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Sinceweignorewhatthegenderofthatpersonisgoingtobe,wesetadefaultvalueforthatmatter.Wealsoadded“Unknown”inordertofillintheemptyspaceincasetherewasnoanswerprovided.

Whilecallingfortheprogram,wesetouroptions,ifit’samale,theywillenter“m”,ifit’safemaleitwillbe“f”,andiftheydon’ttypeanything,thegenderisgoingtobeUnknown.

Thisistheresultwegetafterlaunchingthisprogram.

KeywordArguments

Page 85: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Firstofall,let’sstartwritingourfunctionusingthedefaultvaluesforargumentsthat

wesawpreviouslyinordertobeabletoapplyourmodificationslateron,usingthekeywordargumentsmethod.Ourfunctionwilldifferentfromtheoneprecedingit.Wewillsimplywriteasentenceandplayonwords.

Inthisfunction,weonlyuseddefaultarguments,andtheresultafterlaunchingitisofcoursethefollowing:

However,whatwearegoingtodotothisfunctionismorethanthat.Nowwheneverwewanttopassnewparameters,Pythonisgoingtosetthemintheorderwefirstput(Subject,Verb,Noun).

Forexample,ifwewriteadifferentsentence,likethisone:

Page 86: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Thefunctionwecreatedearliernamed“Sentence”takesthreevariables.Andsincewearepassingthroughanotherthreestringsvariablesrightnowinoursentence(Pythonisawesome),PythonisgoingtoassigneachItemfollowingtheordersweset.Thustheresultisgoingtobe:

Althoughifyouwanttopassitinadifferentorder,whatyouwillhavetodoistousethekeywordoftheargumentyouputatthebeginningwhiledefiningyourfunction.Let’ssaywewouldliketochangetheorderlypositionsofourparameters.

Afterchangingtheorderoftheitems,theresultisthefollowing:

Page 87: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

Inthislastchapteryoulearnthowtodefinefunctions,usefunctionparameters,passstatements,defaultvalueforargumentsandkeywordarguments.

Congratulations!Youhavenowcompletedthisstep-by-stepguideandhavegainedtremendousknowledgeonPython!

Turntonextpagetoseeaquickrecapofwhatwehavecoveredinthisbook.

Page 88: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 89: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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!

Page 90: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called
Page 91: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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.

Page 92: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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

Page 93: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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”

Page 94: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

HereisaPreviewofWhatYouWillLearn:

WhatisSEOandhowitreallyworks?HowsearchenginesoperateLearnthefirststeptogetrankedTheimportanceofkeywordsandhowtodoproperkeywordresearchandanalysecompetitivenessusingfreetoolsOn-pageoptimizationTheuseofHeader,MetaandTitleTagsTrackingyoursite’sperformanceforfree!Off-pageoptimizationandtheuseofpowerfulbacklinks8strategiestogeneratehigh-qualitybacklinksandboostwebsitetrafficWhyIndexingandSitemapsarevitalHowtogenerateandsubmitsitemapsTheimportanceofhigh-qualitycontentHowtocreatehigh-quality,engaginganduniquecontentAndMuchMore!

ClickHereorVisit;http://amzn.to/21HWFWbtoDownloadNow

#1BestSellerintheWeb-DesignandComputers&Technologycategories!

Learnhowtocreateawebsiteusingaverypopularwebdesignplatform,WordPress,withthisNumber1Best-Seller.

Page 95: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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

Page 96: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

“eBay:FindAllYouNeedToSelloneBayandBuildaProfitableBusinessfromScratch,Step-By-Step”

YouWillGainTheFollowingSkills;

WhynowisthebesttimetostartyouronlinebusinessandwhyyouneedtobesellingoneBayHowtheentireprocessworksandwhatstepsyouneedtotaketoopen-upyourownstoretherightwayHowtoknowwhichitemsaremostprofitableandwheretofindthebestsourcesforyourproductsHowtoeffectivelyBrand&PromoteyourbusinessformoreexposureandhigherrevenuesHowtocreateahigh-ranking,eye-catchingandlucrativelisting?Howtotakeyourbusinessandyourincometothenextlevelthroughautomationandoutsourcing?Andmuchmore!

Click-Hereorvisithttp://amzn.to/1R1vnCPtobuythebookNow!

Page 97: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

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])

Page 98: PYTHON: Easy Python Programming For Beginners, Your Step ...index-of.co.uk/Programming/PYTHON Easy Python Programming.pdf · Python is often used by system admins to create the so-called

IthankyouonceagainandGodbless!

FelixAlvaro