python: the ultimate beginner's guide! - andrew johansen.pdf · introduction i want to thank...
TRANSCRIPT
![Page 1: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/1.jpg)
![Page 2: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/2.jpg)
PythonTheUltimateBeginner’sGuide!
AndrewJohansen
![Page 3: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/3.jpg)
Copyright2016byAndrewJohansen-Allrightsreserved.
Thisdocumentisgearedtowardsprovidingexactandreliableinformationinregardstothetopic and issue covered. The publication is soldwith the idea that the publisher is notrequired to render accounting, officially permitted, or otherwise, qualified services. Ifadviceisnecessary, legalorprofessional,apracticedindividual in theprofessionshouldbeordered.
- From a Declaration of Principles which was accepted and approved equally by aCommittee of the American Bar Association and a Committee of Publishers andAssociations.
Innowayisitlegaltoreproduce,duplicate,ortransmitanypartofthisdocumentineitherelectronicmeansorinprintedformat.Recordingofthispublicationisstrictlyprohibitedandanystorageofthisdocumentisnotallowedunlesswithwrittenpermissionfromthepublisher.Allrightsreserved.
Theinformationprovidedhereinisstatedtobetruthfulandconsistent,inthatanyliability,intermsofinattentionorotherwise,byanyusageorabuseofanypolicies,processes,ordirectionscontainedwithinis thesolitaryandutterresponsibilityof therecipientreader.Under no circumstances will any legal responsibility or blame be held against thepublisher for any reparation, damages, ormonetary loss due to the information herein,eitherdirectlyorindirectly.
Respectiveauthorsownallcopyrightsnotheldbythepublisher.
Theinformationhereinisofferedforinformationalpurposessolely,andisuniversalasso.Thepresentationoftheinformationiswithoutcontractoranytypeofguaranteeassurance.
Thetrademarksthatareusedarewithoutanyconsent,andthepublicationofthetrademarkis without permission or backing by the trademark owner. All trademarks and brandswithin this book are for clarifying purposes only and are the owned by the ownersthemselves,notaffiliatedwiththisdocument.
![Page 4: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/4.jpg)
TableofContentsIntroduction
Chapter1GettingAcquaintedwithPython
Chapter2InstallingPython
Chapter3InteractingwithPython
Chapter4PythonSyntax
Chapter5VariablesandDataTypes
Chapter6BasicOperators
Chapter7Built-inFunctions
Chapter8ConditionalStatements
Chapter9Loops
Chapter10User-DefinedFunctions
Chapter11IntroductiontoClassesandObject-OrientedProgramming
Conclusion
![Page 5: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/5.jpg)
Introduction
Iwanttothankyouandcongratulateyouforpurchasingthisbook…
“Python:TheUltimateBeginner’sGuide!”
ThisbookcontainsprovenstepsandstrategiesonlearningPythonProgrammingquicklyandeasily.
Pythonisapowerfulandflexibleprogramminglanguage.Itusesconciseandeasy-to-learnsyntax which enables programmers to write more codes and develop more complexprogramsinamuchshortertime.
Python:TheUltimateBeginner’sGuideprovidesallessentialprogrammingconceptsandinformationyouneedtostartdevelopingyourownPythonprogram.Thebookprovidesacomprehensivewalk-throughofPythonprogramming inaclear, straightforwardmannerthatbeginnerswill appreciate. Important concepts are introduced througha step-by-stepdiscussionandreinforcedbyrelevantexamplesandillustrations.Youcanusethisbookasaguidetohelpyouexplore,harness,andgainappreciationofthecapabilitiesandfeaturesofPython.
Thanksagainforpurchasingthisbook,Ihopeyouenjoyit!
![Page 6: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/6.jpg)
Chapter1GettingAcquaintedwithPython
Python is an open source, high-level programming language developed by Guido vanRossuminthelate1980sandpresentlyadministeredbyPythonSoftwareFoundation.ItcamefromtheABClanguagethathehelpedcreateearlyoninhiscareer.
Pythonisapowerfullanguagethatyoucanusetocreategames,writeGUIs,anddevelopwebapplications.
Itisahigh-levellanguage.ReadingandwritingcodesinPythonismuchlikereadingandwriting regular English statements. Because they are not written in machine-readablelanguage,Pythonprogramsneedtobeprocessedbeforemachinescanrunthem.
Python is an interpreted language. This means that every time a program is run, itsinterpreterrunsthroughthecodeandtranslatesitintomachine-readablebytecode.
Python is an object-oriented language that allows users to manage and control datastructures or objects to create and run programs. Everything in Python is, in fact, firstclass. All objects, data types, functions, methods, and classes take equal position inPython.
Programminglanguagesarecreatedtosatisfytheneedsofprogrammersandusersforaneffective tool todevelopapplications that impact lives, lifestyles, economy,and society.They helpmake lives better by increasing productivity, enhancing communication, andimproving efficiency. Languages die and become obsolete when they fail to live up toexpectations and are replaced and superseded by languages that are more powerful.Python is a programming language that has stood the test of time and has remainedrelevantacrossindustriesandbusinessesandamongprogrammers,andindividualusers.Itis a living, thriving, and highly useful language that is highly recommended as a firstprogramminglanguageforthosewhowanttodiveintoandexperienceprogramming.
AdvantagesofUsingPython
Here are reasonswhy youwould prefer to learn and use Python over other high levellanguages:
Readability
![Page 7: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/7.jpg)
Pythonprogramsuseclear,simple,andconciseinstructionsthatareeasytoreadevenbythosewhohavenosubstantialprogrammingbackground.ProgramswritteninPythonare,therefore,easiertomaintain,debug,orenhance.
Higherproductivity
CodesusedinPythonareconsiderablyshorter,simpler,andlessverbosethanotherhigh-level programming languages such as Java and C++. In addition, it has well-designedbuilt-infeaturesandstandardlibraryaswellasaccesstothirdpartymodulesandsourcelibraries.ThesefeaturesmakeprogramminginPythonmoreefficient.
Lesslearningtime
Python is relatively easy to learn.Many findPython a good first language for learningprogrammingbecauseitusessimplesyntaxandshortercodes.
Runsacrossdifferentplatforms
PythonworksonWindows,Linux/UNIX,MacOSX,otheroperatingsystemsandsmall-formdevices. It also runsonmicrocontrollersused inappliances, toys, remotecontrols,embeddeddevices,andothersimilardevices.
![Page 8: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/8.jpg)
Chapter2InstallingPython
InstallingPythoninWindows
To install Python, you must first download the installation package of your preferredversionfromthislink:
https://www.python.org/downloads/
Onthispage,youwillbeaskedtochoosebetweenthetwolatestversionsforPython2and3:Python3.5.1andPython2.7.11.Alternatively,ifyouarelookingforaspecificrelease,youcanscrolldownthepagetofinddownloadlinksforearlierversions.
Youwouldnormallyopttodownloadthelatestversion,whichisPython3.5.1.ThiswasreleasedonDecember7,2015.However,youmayoptforthelatestversionofPython2,2.7.11.Your preferenceswill usually depend onwhich versionwill bemost usable foryourproject.WhilePython3isthepresentandfutureofthelanguage,issuessuchasthirdpartyutilityorcompatibilitymayrequireyoutodownloadPython2.
InstallingPythoninMac
![Page 9: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/9.jpg)
Ifyou’reusingaMac,youcandownloadtheinstallationpackagefromthislink:
https://www.python.org/downloads/mac-osx/
RunningtheInstallationfile:
Onceyou’refinishedwiththedownload,youcanproceedtoinstallationbyclickingonthedownloaded.exefile.StandardinstallationwillincludeIDLE,pip,anddocumentation.
![Page 10: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/10.jpg)
Chapter3InteractingwithPython
Pythonisaflexibleanddynamiclanguagethatyoucanuseindifferentways.Youcanuseitinteractivelywhenyousimplywanttotestacodeorastatementonaline-by-linebasisorwhenyou’re exploring its features.You canuse it in scriptmodewhenyouwant tointerpretanentirefileofstatementsorapplicationprogram.
TousePythoninteractively,youcanuseeithertheCommandLinewindowortheIDLEDevelopmentEnvironment.
CommandLineInteraction
ThecommandlineisthemoststraightforwardwaytoworkwithPython.YoucaneasilyvisualizehowPythonworksas it responds toeverycompletedcommandenteredon the>>> prompt. It may not be the most preferred interaction with Python, but it is thesimplestwaytoexplorehowPythonworks.
StartingPython
There are differentways to access Python’s command line depending on the operatingsysteminstalledonyourmachine:
Ifyou’reusingWindows,youcanstartthePythoncommandlinebyclickingonitsiconormenuitemontheStartmenu.
YoumayalsogotothefoldercontainingtheshortcutortheinstalledfilesandclickonthePythoncommandline.
Ifyou’reusingGNU/Linux,UNIX,andMacOSsystems,youhavetoruntheTerminalToolandenterthePythoncommandtostartyoursession.
We use commands to tell the computer what to do. When you want Python to dosomethingforyou,youhavetoinstructitbyenteringcommandsthatit isfamiliarwith.Pythonwill then translate these commands to instructions that your computerordevicecanunderstandandexecute.
![Page 11: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/11.jpg)
ToseehowPythonworks,youcanusetheprintcommandtoprinttheuniversalprogram“Hello,World!”
1.OpenPython’scommandline.
2.Atthe>>>prompt,typethefollowing:
print(“Hello,World!”)
3.PressentertotellPythonthatyou’redonewithyourcommand.Veryquickly,thecommandlinewindowwilldisplayHello,World!onthefollowingline:
Pythonrespondedcorrectlybecauseyougaveitacommandinaformatthatitrequires.Toseehowitrespondswhenyouaskittoprintthesamestringusingawrongsyntaxfortheprintcommand,typeandenterthefollowingcommandonthePythoncommandprompt:
![Page 12: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/12.jpg)
Print(“Hello,World!”)
ThisishowPythonwillrespond:
Syntaxerror:invalidsyntax
You’llgetsyntaxerrormessageswheneveryouenterinvalidorincompletestatements.Inthis case, you typed print with a capital letter which is a big no to a case-sensitivelanguagelikePython.
Ifyou’rejustusingPythoninteractively,youcandoawaywiththeprintcommandentirelybyjusttypingyourstatementwithinquotessuchas“Hello,World!”
ExitingPython
ToexitfromPython,youcantypeanyofthesecommands:
quit()
exit()
Control-Zthenpressenter
IDLE:Python’sIntegratedDevelopmentEnvironment(IDE)
The IDLE (Integrated Development and Learning Environment) tool is included inPython’s installation package but you can choose to downloadmore sophisticated thirdpartyIDEs.
TheIDLEtooloffersamoreefficientplatformtowriteyourcodeandworkinteractively
![Page 13: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/13.jpg)
withPython.YoucanaccessIDLEonthesamefolderwhereyoufoundthecommandlineiconoronthestartmenu.AssoonasyouclickontheIDLEicon,itwilltakeyoutothePythonShellwindow.
ThePythonShellWindow
The Python ShellWindow has dropdownmenus and a >>>prompt that you have seenearlier in the command line window. Here you can type and enter statements orexpressionsforevaluationinthesamewaythatyouusedthecommandlineearlier.Thistimehowever,IDLE’seditingmenuallowsyoutoscrollbacktoyourpreviouscommands,cut, copy, and paste previous statements andmakemodifications. IDLE is quite a leapfromthecommandlineinteraction.
The Python Shell window has the following menu items: File, Edit, Shell, Debug,Options,Windows,andHelp.
![Page 14: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/14.jpg)
The Shell and Debugmenus provide capabilities youwould find useful when creatinglargerprograms.
TheShellmenuallowsyou to restart theshellorsearch theshell’s log to find themostrecentreset.
TheDebugMenuhasusefulmenu items for tracing the source fileofanexceptionandhighlighting the erring line. TheDebugger optionwill usher in an interactive debuggerwindowthatwillallowyoutostepthroughtherunningprogram.TheStackVieweroptiondisplaysthecurrentPythonstackthroughanewwindow.
The Options window allows you to configure IDLE to suit your Python workingpreferences.
TheHelpoptionopensPythonHelpanddocumentation.
TheFileWindow
The items on the File menu allows you to create a new file, open an old file, open amodule,and/orsaveyoursession.Whenyouclickonthe‘NewFile’option,youwillbetakentoanewwindow,asimpleandstandardtexteditorwhereyoucantypeoredityourcode.Initially,thisfilewindowisnamed‘untitled’butitsnamewillsoonchangeasyousaveyourcode.
TheFilewindow’smenubarvariesonlyslightlywiththeShellWindow.Itdoesn’thavethe ‘Shell’ and ‘Debug’ menu found in the Shell Window but it introduces two newmenus: theRun and the Formatmenu.When you choose toRun your code on the filewindow,youcanseetheoutputontheShellWindow.
![Page 15: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/15.jpg)
TheScriptMode
Whenworkinginscriptmode,youwon’tautomaticallyseeresultsthewayyouwouldininteractive mood. To see an output from a script, you’ll have to run the script and/orinvoketheprint()functionwithinyourcode.
![Page 16: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/16.jpg)
Chapter4PythonSyntax
Python syntax refers to the set of rules that defines how human users and the systemshouldwriteandinterpretaPythonprogram.IfyouwanttowriteandrunyourprograminPython,youmustfamiliarizeyourselfwithitssyntax.
Keywords
Python keywords are reserved words in Python that should not be used as variable,constant, functionname,or identifier inyour code.Takenoteof thesekeywords if youdon’twanttorunintoerrorswhenyouexecuteyourprogram:
andassert
breakclass
continuedef
delelif
elseexcept
execfinally
forfrom
globalif
importin
islambda
notor
passprint
raisereturn
trywhile
withyield
PythonIdentifiers
APythonIdentifierisanamegiventoafunction,class,variable,module,orotherobjectsthatyou’llbeusinginyourPythonprogram.Anyentityyou’llbeusinginPythonshouldbeappropriatelynamedoridentifiedastheywillformpartofyourprogram.
![Page 17: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/17.jpg)
HerearePythonnamingconventionsthatyoushouldbeawareof:
Anidentifiercanbeacombinationofuppercaseletters,lowercaseletters,underscores,and digits (0-9). Hence, the following are valid identifiers: myClass, my_variable,var_1,andprint_hello_world.
Specialcharacterssuchas%,@,and$arenotallowedwithinidentifiers.An identifier should not begin with a number. Hence, 2variable is not valid, butvariable2isacceptable.
Python is a case-sensitive language and this behavior extends to identifiers. Thus,LaborandlaboraretwodistinctidentifiersinPython.
YoucannotusePythonkeywordsasidentifiers.
Classidentifiersbeginwithanuppercaseletter,buttherestoftheidentifiersbegininlowercase.
Youcanuseunderscorestoseparatemultiplewordsinyouridentifier.
Youshouldalwayschooseidentifiers thatwillmakesense toyouevenaftera longgap.Hence,while it iseasy to setyourvariable toc=2,youmight find itmorehelpful forfuturereferenceifyouusealongerbutmorerelevantvariablenamesuchascount=2.
UsingQuotations
Pythonallows theuseofquotationmarks to indicate string literals.Youcanuse single,double, or triple quotes but youmust start and end the stringwith the same type.Youwouldusethetriplequoteswhenyourstringrunsacrossseverallines.
PythonStatements
![Page 18: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/18.jpg)
StatementsareinstructionsthataPythoninterpretercanexecute.Whenyouassignavalueto a variable, say my_variable = “dog”, you’re making an assignment statement. Anassignmentstatementmayalsobeasshortasc=3.ThereareotherkindsofstatementsinPython,likeifstatements,whilestatements,forstatements,etc.
Multi-linestatements
Astatementmayspanover several lines.Tobreaka longstatementovermultiple lines,youcanwraptheexpressioninsideparentheses,braces,andbrackets.Thisisthepreferredstyleforhandlingmulti-lineexpressions.Anotherwaytowrapmultiplelinesisbyusingabackslash(\)attheendofeverylinetoindicatelinecontinuation.
Indentation
WhilemostprogramminglanguagessuchasJava,C,andC++usebracestodenoteblocksofcode,Pythonprogramsarestructuredthroughindentation.InPython,blocksofcodesaredefinedby indentationnotasamatterof styleorpreferencebutasa rigid languagerequirement.ThisprinciplemakesPythoncodesmorereadableandunderstandable.
AblockofcodecanbeeasilyidentifiedwhenyoulookataPythonprogramastheystarton the same distance to the right. If it has to bemore deeply nestled, you can simplyindent another block further to the right. For example, here is a segment of a programdefiningcar_rental_cost:
defcar_rental_cost(days):
cost=35*days
ifdays>=8:
cost-=70
elifdays>=3:
cost-=20
returncost
![Page 19: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/19.jpg)
Youhavetomakesurethat theindentspaceisconsistentwithinablock.WhenyouuseIDLEandotherIDEstoinputyourcodes,Pythonintuitivelyprovidesindentationonthesubsequent line when you enter a statement that requires indentation. Indentation, byconvention,isequivalentto4spacestotheright.
Comments
When writing a program, you’ll find it helpful to put some notes within your code todescribewhatitdoes.Acommentisveryhandywhenyouhavetorevieworrevisityourprogram.Itwillalsohelpanotherprogrammerwhomightneedtogooverthesourcecode.Youcanwritecommentswithinyourprogrambystartingthelinewithahash(#)symbol.A hash symbol tells the Python interpreter to ignore the comment when running yourcode.
For multi-line comments, you can use a hash symbol at the beginning of each line.Alternatively,youcanalsowrapmulti-linecommentwithtriplequotes.
![Page 20: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/20.jpg)
Chapter5VariablesandDataTypes
Variables
Avariableislikeacontainerthatstoresvaluesthatyoucanaccessorchange.Itisawayofpointingtoamemorylocationusedbyaprogram.Youcanusevariablestoinstructthecomputertosaveorretrievedatatoandfromthismemorylocation.
Python differs significantly from languages such as Java, C, or C++when it comes todealingwithvariables.Otherlanguagesdeclareandbindavariabletoaspecificdatatype.Thismeansthatitcanonlystoreauniquedatatype.Hence,ifavariableisofintegertype,youcanonlysaveintegersinthatvariablewhenrunningyourprogram.
Pythonisalotmoreflexiblewhenitcomestohandlingvariables.Ifyouneedavariable,you’ll just thinkofanameanddeclare itbyassigningavalue. Ifyouneed to,youcanchangethevalueanddatatypethatthevariablestoresduringprogramexecution.
Toillustratethesefeatures:
InPython,youdeclareavariablebygivingitavalue:
my_variable=10
Take note thatwhen you are declaring a variable, you are not stating that the variablemy_variable isequal to10.What thestatementactuallymeans is“my_variable isset to10”.
Toincreasethevalueofthevariable,youcanenterthisstatementonthecommandline:
>>>my_variable=my_variable+3
![Page 21: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/21.jpg)
To see how Python responded to your statement, invoke the print command with thisstatement:
>>>print(my_variable)
You’llseethisresultonthenextline:
13
To use my_variable to store a literal string “yellow”, you’ll simply set the variable to“yellow”:
>>>my_variable=“yellow”
Toseewhat’scurrentlystoreinmy_variable,usetheprintcommand:
>>>print(my_variable)
Onthenextline,you’llsee:
yellow
DataTypes
Pythonhandlesseveraldatatypestofacilitatetheneedsofprogrammersandapplicationdevelopers forworkabledata.These include strings,numbers,Booleans, lists, date, andtime.
Strings
![Page 22: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/22.jpg)
A string is a sequence of Unicode characters that may be a combination of letters,numbers,andspecialsymbols.TodefineastringinPython,youcanenclosethestringinmatchingsingleordoublequotes:
>>>string1=“Iamenclosedinsinglequotes.”
>>>string2=“Iamenclosedindoublequotes.”
Ifaliteralstringenclosedinsinglequotescontainsasinglequote,you’llhavetoplaceabackslash(\)beforethesinglequotewithinthestringtoescapethecharacter.Forexample:
>>>string3=‘Itdoesn'tlookgoodatall.’
Toprintstring3:
>>>print(string3)
Itdoesn’tlookgoodatall.
Ofcourse,youwouldn’thavetodothisifyouuseddoublequotestoenclosethestring:
>>>string3=“Itdoesn’tseemnice”
Similarly,you’llhavetoplaceabackslashbeforeadoublequoteifyourstringisenclosedindoublequotes:
>>>txt=“Hesaid:\“Youshouldgetthesameresultsnomatterhowyouchoosetoencloseastring.\””
>>>print(txt)
Hesaid:“Youshouldgetthesameresultsnomatterhowyouchoosetoencloseastring.”
Stringsmaybeindexedorsubscripted.InPython,indexingstartsfrom0(zero)insteadof1.Hence,astring’sfirstcharacterhasazeroindex.
![Page 23: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/23.jpg)
ToillustratehowstringindexingworksinPython,definethestring“HelloPython”onthecommandline:
>>>s=“HelloPython”
ThisishowPythonwouldindexthestring:
-12 -11 -10 -9 -8 -6 -6 -5 -4 -3 -2 -1
H e l l o P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11
To access the first character on the string you just created, type and enter the variablenamesandtheindex0withinsquarebracketslikethis:
>>>s[0]
You’llgetthisoutput:
‘H’
Accessingthefirstcharacteriseasybecauseyouknowthatitsindexnumberiszero.Youdonothavethisadvantagewhenyouwanttoaccessthelastcharacteronthestring.
Toaccessthelastcharacter,youcanusethisexpression:
>>>s[len(s)-1]
You’llgettheoutput:
![Page 24: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/24.jpg)
‘n’
The expression introduces you to the len function. There is actually an easier way toaccessthelastitemonthestring:
>>>s[-1]
‘n’
Toaccessthepenultimatecharacter:
>>>s[-2]
‘o’
Besidesindexing,youcanuseotherfunctionsandmathematicaloperatorsonastring.
ConcatenatingStrings
Strings can be added together with plus (+) operator. To concatenate the string “HelloPython”:
>>> “Hello”+“Python”
‘HelloPython’
RepeatingStrings
Youcaneasilyrepeatstringsoritsconcatenationwiththe*operator.Forexample:
Entering“**^**”*5willyield:
‘**^****^****^****^****^**’
![Page 25: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/25.jpg)
You’llgetthesameresultwiththis:
>>>s=“**^**”
>>>s*5
‘**^****^****^****^****^**’
GettingtheSizeofStrings
Youcangetthesizeofastringwiththelen()function.Forexample,togetthesizeofthestring“World”:
>>>len(“World”)
5
SlicingStrings
Youcancreatesubstringswiththeslicingnotation.Youcandothisbyplacingtwoindices(separated by a colon) within square brackets. The first index marks the start of thesubstringwhile the second index indicates the index number of the first character youdon’twanttoincludeinthesubstring.
Forexample:
>>>“Program”[3:5]
willresultin:
‘gr’
>>>“Program”[3:6]
willyield:
![Page 26: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/26.jpg)
‘gra’
Another way of doing this is by storing “Program” to a variable andmanipulating thevariabletoproducethedesiredresult:
>>>p=“Program”
>>>p[3:6]
‘gra’
Ifyouwantthesubstringtostartfromacharactertotheendoftheoriginalstring,youcanjustomitthesecondindex.Forexample:
>>>p=“Program”
>>>p[4:]
‘ram’
Conversely, if you want your substring to start from the first character of the originalstring,youcanomitthefirstindexandwritethelastindextobeincludedonthesubstring.Forexample:
>>>p=“Program”
>>>p[:4]
‘Prog’
Thelower()andupper()function
Ifyouhaveastringlike“GrandRiver”andyouhavedecidedthatyouneedyourdatatobeallinlowercase,youcanusethelower()functiontoprintthestringinlowercase.
Example:
![Page 27: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/27.jpg)
>>>c=“GrandRiver”
>>>print(c.lower())
grandriver
Supposingyouneedyoustringtobeallcapitalized,youcaninvoketheupper() functiontoprintthestringinuppercase.
Example:
>>>print(c.upper())
GRANDRIVER
Thestr()method
Thestr()functionmakesstringsoutofnon-stringscharacter.Thisallowsprogrammerstoprintnon-stringcharactersas if theyarestringcharacters.This isveryhandywhenyouwant,forinstance,toprintanintegeralongwithstrings.
Example:
>>>pi=3.1416
>>>str(pi)
‘3.1416’
>>>print(“Thismyfavoritenumber:”+str(pi))
Thismyfavoritenumber:3.1416
![Page 28: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/28.jpg)
Numbers
NumericDataTypes
OneofthemanyconveniencesofusingPythonisthatyoudon’treallyhavetodeclareanumericvaluetodistinguishits type.Pythoncanreadilytellonedatatypefromanotherwhenyouwriteandrunyourstatement.Ithasfourbuilt-innumericdatatypes.Python3supportsthreetypes:integer,floating-pointnumbers,andcomplexnumbers.Longintegers(‘long’)nolongerformaseparategroupofintegersbutareincludedinthe‘int’orintegercategory.
1. Integer(int)
Integers arewhole numberswithout decimal point.They canbe positive or negative aslongastheydon’tcontainadecimalpointthatwouldmakeanumberafloatingnumber,adistinctnumerictype.IntegershaveunlimitedsizeinPython3.
ThefollowingnumbersandliteralsarerecognizedbyPython:
Regularintegers
Examples:793,-254,4
Octalliterals(base8)
Toindicateanoctalnumber,youwillusetheprefix0oor0O(zerofollowedbyeitheralowercaseoruppercaseletter‘o’).
Example:
>>>a=0O7
![Page 29: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/29.jpg)
>>>print(a)
7
Hexadecimalliterals(base16)
Toindicatehexadecimalliterals,youwillusetheprefix‘0X’or‘0x”(zeroanduppercaseorlowercaseletter‘x’).
Example:
>>>hex_lit=0xA0C
>>>print(hex_lit)
2572
Binaryliterals(base2)
To signify binary literals, you’ll use the prefix ‘0B’ or ‘0b’ (zero and uppercase orlowercase‘b’).
Example:
>>>c=0b1100
>>>print(c)
12
ConvertingIntegerstotheirStringRepresentation
Earlier, you have seen how the print command converted literals to their equivalent inintegers.Pythonmakes it possible foryou towork theotherwayaroundby converting
![Page 30: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/30.jpg)
integerstotheirliteralrepresentation.Toconvertanintegerintoitsstringrepresentation,youcanusethefunctionshex(),bin(),andoct().
Examples:
Toconverttheinteger7toitsoctalliteral,typeandenteroct(7)onthecommandprompt.You’llgettheoutput‘0o7’:
>>>oct(7)
‘0o7’
Hereiswhathappenswhenyouconverttheinteger2572toahexadecimalliteral:
>>>hex(2572)
‘0xa0c’
Finally,seewhathappenswhenyouusethebin()functiontoconverttheinteger12toitsbinarystring:
>>>bin(12)
‘0b1100’
Youcanstoretheresulttoavariablebydefiningavariablewiththehex(),bin(),andoct()functions:
Forexample:
>>>x=hex(2572)
>>>x
‘0xa0c’
![Page 31: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/31.jpg)
To see the object type created and stored in the variable x, you can use and enter thecommandtype():
>>>type(x)
Youshouldgetthisresult:
<class‘str’>
2. Floating-pointnumbers
Alsoknownasfloats,floating-pointnumberssignifyrealnumbers.Floatsarewrittenwithadecimalpointthatsegregatestheintegerfromthefractionalnumbers.Theymayalsobewritteninscientificnotationwheretheuppercaseorlowercaseletter‘e’signifiesthe10thpower:
>>>6.2e3
6200.0
>>>6.2e2
620
3. Complexnumbers
Complexnumbersarepairsofrealandimaginarynumbers.Theytaketheform‘a+bJ’where‘a’isafloatandtherealpartofthecomplexnumber.OntheothersideisbJwhere‘b’isafloatandJoritslowercaseindicatesthesquarerootofanimaginarynumber,-1.Thismakes‘b’theimaginarypartofthecomplexnumber.
Hereareexamplesofcomplexnumbersatwork:
>>>a=2+5j
![Page 32: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/32.jpg)
>>>b=4–2j
>>>c=a+b
>>>print(c)
(6+3j)
ComplexnumbersarenotextensivelyusedinPythonprogramming.
ConversionofNumberType
YoucanexpectPythontoconvertexpressionswithmixedtypesofnumberstoacommontype to facilitate evaluation. In some situations, however, youmayhave to convert onenumber type to another explicitly, like when the conversion is required by a functionparameter.Youcantypethefollowingexpressionstoconvertanumbertoanothertype:
Toconvertxtoafloat:>>>float(x)
Example:
>>>float(12)
12.0
Toconvertxtoaplaininteger:int(x)
>>>int(12)
12
Toconvertxtoacomplexnumber:typecomplex(x)
>>>complex(12)
![Page 33: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/33.jpg)
(12+0j)
DateandTime
Most applications require date and time information to make it work efficiently andeffectively.InPython,youcanusethefunctiondatetime.now()toretrievethecurrentdateand time.Thecommanddatetime.now()callsonabuilt-inPythoncodewhichgives thecurrentdateandtime.
TogetthedateandtimefromPython,encodethefollowingonthecommandprompt:
>>>fromdatetimeimportdatetime
>>>datetime.now()
datetime.datetime(2016,3,10,2,16,19,962429)
Thedateandtimeinthisformatisalmostunintelligibleandyoumightwanttogetaresultthat ismore readable.Oneway todo this is byusing ‘strftime’ fromPython’s standardlibrary.
Tryenteringthesecommandsandseeifyou’llgettheformatyoulike.
>>>fromtimeimportstrftime
>>>strftime(“%Y-%m-%d%H:%M:%S”)
‘2016-03-1002:20:03’
BooleanDataType
Comparisons inPythoncanonlygenerateoneof twopossible responses:TrueorFalse.Thesedatatypesarecalledbooleans.
Toillustrate,youcancreateseveralvariablestostoreBooleanvaluesandprinttheresult:
![Page 34: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/34.jpg)
bool_1=4==2*3
bool_2=10<2*2**3
bool_3=8>2*4+1
print(bool_1)
print(bool_2)
print(bool_3)
ThePythonShellwilldisplaytheseresults:
False
True
False
Lists
A list is a data type that can be used to store any type and number of variables andinformation.
Youcandefineandassignitemstoalistwiththeexpression:
my_list=[item_1,item_2,item_3]
Pythonalsoallowscreationofanemptylist:
my_list=[]
Toillustrate,let’screatealistofcolors:
![Page 35: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/35.jpg)
colors=[“red”,“orange”,“yellow”,“green”,“indigo”,“white”]
Sincethisisanindexedlist,thefirstitemoncolorshaszeroasitsindex.
Toaccessthefirstitemonthelist,youcanprintthecolorwiththecommand:
>>>print(colors[0])
red
Toprintthecolornameofthethirdcoloronthelist,youcanenter:
>>>print(colors[4])
indigo
Toseehowmanycolorsareonthelist,youcanusethelen()function:
>>>len(colors)
6
Thereareonlysixcolorsonyourlistbutyouwanttohaveallsevencolorsoftherainbowin your list. To seewhat colors are on the list, you can use the print to seewhat colormightbemissing:
>>>print(colors)
[‘red’,‘orange’,‘yellow’,‘green’,‘indigo’,‘white’]
Itappearsthatthecolorslistdoesn’tjustlackonecolorname.Italsohasonememberthatshouldnothavebeenincluded–‘white’.Toremove‘white’fromthelist,youcanusetheremove()method:
>>>colors.remove(“white”)
Youcanviewtheupdatedlistwiththeprintcommand:
![Page 36: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/36.jpg)
>>>print(colors)
[‘red’,‘orange’,‘yellow’,‘green’,‘indigo’]
Thelistisstillshortof2colors–violetandblue.
Toaddviolettoyourcolorslist,youcanusetheappendcommand:
>>>colors.append(“violet”)
Let’scheckouttheupdatedlistwiththeprintcommand:
>>>print(colors)
[‘red’,‘orange’,‘yellow’,‘green’,‘indigo’,‘violet’]
Thecolor‘violet’wasaddedtotheendofthelist.Now,youonlyneedtoaddonemorecolor-blue.Let’ssayyouwanttohave‘blue’insertedbetween‘green’and‘indigo’.
YoucanusePython’sinsert()methodwiththesyntax:
list.insert(index,obj)
Theparametersareindexandobject.Indexreferstothepositionwhereyouwantthenewitemtobelocated.Theobjectistheitemyouwanttoinsert.
Applyingthesyntaxtotheaboveexample,you’llhavethecommand:
>>>colors.insert(4,“blue”)
Toseethenewlist:
>>>print(colors)
[‘red’,‘orange’,‘yellow’,‘green’,‘blue’,‘indigo’,‘violet’]
![Page 37: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/37.jpg)
Slicinglists
Youcanalsoslicelistsinthesamewaythatyouslicestrings.
For example, if you onlywant to display the colors ‘green’, ‘blue’, and ‘indigo’, withindexof3,4,5respectively,youcanusethiscommand:
>>>colors[3:6]
[‘green’,‘blue’,‘indigo’]
Dictionary
Adictionary is likea listbut insteadof lookingupan index toaccessvalues,you’llbeusing a unique key, which can be a number, string, or tuple. Dictionary values can beanythingbut thekeysmustbeanimmutabledata type.Acolonseparatesakeyfromitsvalueandallareenclosedincurlybraces.Hereisthedictionarystructure:
d={key_1:a,key_2:2,key_3:ab}
Anemptydictionarywillhavethisformat:
d={}
Adictionarycanbeaveryusefultoolforstoringandmanipulatingkey-valuepairssuchasthoseusedinphonebooks,directory,menu,orlog-indata.Youcanadd,modify,ordeleteexistingentrieswithinthedictionary.
Toseehowdictionariesactuallywork,youcancreateadictionarynamedmenuwithdishandpricespairs:
menu={“spam”:12.50,“carbonara”:20,“salad”:15}
![Page 38: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/38.jpg)
To see how many key-value pairs are stored in the dictionary, you can use the len()function:
>>>len(menu)
3
Toprintthecurrententriesinthemenudictionary:
>>>print(menu)
{‘salad’:15,‘carbonara’:20,‘spam’:12.5}
Toaddanotherentryinthemenudictionary,youcanusethisformat:
d[key_4:b]
Applyingthisstructuretothemenudictionary,youcanaddthedish-priceentryofcake:6with:
menu[“cake”]=6
Toseetheupdatedmenu,usetheprintcommand:
>>>print(menu)
{‘spam’:12.5,‘cake’:6,‘carbonara’:20,‘salad’:15}
Assumingyounolongerwanttoincludespaminyourmenu,youcaneasilydosowiththedelcommand:
>>>delmenu[“spam”]
Toseethemodifiedlistafterdeletingspam:
![Page 39: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/39.jpg)
{‘cake’:6,‘carbonara’:20,‘salad’:15}
Youmightwant tochange thevalues inanyof thekeysatonepoint.For instance,youneedtochangethepriceofcarbonarafrom20to22.Todothat,you’lljustassignanewvaluetothekeywiththiscommand:
>>>menu[“carbonara”]=22
Youcanusetheprintcommandoncemoretoseetheupdatedmenu:
>>>print(menu)
{‘cake’:6,‘carbonara’:22,‘salad’:15}
Ifyouwanttoremoveallentriesinthedictionary,youcanusethefunction
dict.clear()
Toclearallentriesinthemenu:
>>>dict.clear(menu)
Usetheprintcommandtoseewhathappenedtothemenudictionary:
>>>print(menu)
{}
The Python Shell displayed an empty dictionary with the clear command. Now that itcontainsnodataatall,youmightdecidetodeletethedictionary.Youcandosowiththedelcommand:
deldict
![Page 40: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/40.jpg)
Todeletethemenudictionary:
delmenu
Toseewhathappened,usetheprintcommand.
>>>print(menu)
Traceback(mostrecentcalllast):
File“<pyshell#19>”,line1,in<module>
print(menu)
NameError:name‘menu’isnotdefined
Yougotanerrormessagebecausemenunolongerexists.
Chapter6PythonBasicOperators
Pythonoperatorsallowprogrammerstomanipulatedataoroperands.HerearethetypesofoperatorssupportedbyPython:
ArithmeticOperatorsAssignmentOperatorsRelationalorComparisonOperatorsLogicalOperatorsIdentityOperatorsBitwiseOperatorsMembershipOperators
ArithmeticOperators
Pythondoesagoodjobofprocessingmathematicalexpressionswithitsbasicarithmetic
![Page 41: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/41.jpg)
operators.Youcaneasilymakeprogramstoautomatetaskssuchascomputingtax,tips,discounts,orrent.
+ Addition addsthevalueoftheleftandrightoperands
- Subtractionsubtractsthevalueoftherightoperandfromthevalueoftheleftoperand
* Multiplication multipliesthevalueoftheleftandrightoperand
/ Divisiondividesthevalueoftheleftoperandbytherightoperand
** Exponent performsexponentialcalculation
% Modulusreturnstheremainderafterdividingtheleftoperandwiththerightoperand
//FloorDivision
divisionofoperandswherethesolutionisaquotientleftafterremovingdecimalnumbers
Addition, subtraction,multiplication, and division are themost basic operators and areinvokedbyenteringthefollowingexpressions:
Addition:
>>>1+3
4
Subtraction:
>>>10–4
6
Multiplication:
>>>4*2
![Page 42: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/42.jpg)
8
Division:
>>>10/2
5.o
Exponent
Exponentialcalculationisinvokedbyraisingthefirstnumbertothepowerdefinedbythenumberafterthe**operator:
>>>2**32raisedtothepowerof3
8
Modulus
Themodulusoperatorgivestheremainderafterperformingdivision:
>>>17%5
2
FloorDivision
Floordivision,ontheotherhand,returnsthequotientafterremovingfractionalnumbers:
>>>17//5
3
![Page 43: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/43.jpg)
UsingBasicOperatorstoComputeSalesTax,Tip,andTotalBill
Toputyourknowledgeofvariables,datatypes,andoperatorstogooduse,youcandesignasimpleprogramthatwillcomputethesalestaxandtiponarestaurantmeal.
Mealcost$65.50
Salestaxrate6.6%
Tip20%ofmeal+tax
First,setupavariablemealtostorethefoodcost:
meal=65.50
Next, set up the tax and tip variable. Assign both variables the decimal value of thepercentagesgiven.Youcandothisbyusing100asdivisor.
tax=6.6/100
tip=20/100
Yourtipisbasedonmealcostandtheaddedsalestaxsoyouneedtogetthetotalamountofthemealandthesalestax.Onewaytodothisisbysimplycreatinganewvariabletostorethetotalcostofthemealandtax.Anotherwayisbyreassigningthevariablemealsothatitstoresbothvalues:
meal=meal+meal*tax
Nowthatyouhavereassignedmealtotakecareofthemealcostandtax,you’rereadytocompute for the tip.This time,youcan set anewvariable to store thevalueof the tip,meal,andtax.Youcanusethevariabletotaltoholdallvalues:
total=meal*tip
Here’syourcodetocomputeforthetotalbillamount:
![Page 44: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/44.jpg)
meal=65.50
tax=6.6/100
tip=20/100
meal=meal+meal*tax
total=meal+meal*tip
Ifyou’reusingthefileeditorinIDLE,youcansavethefileinafilenameofyourchoiceandPythonautomatically appends the .pyextension.Asyoumayhavenoticed, the fileeditorwillalwayspromptyoutosaveyourfilebeforeitdoesanythingaboutyourcode.Just like when naming other data files and types, you should use a filename that’sdescriptiveofthefile.Inthiscase,afilenamelikeBillCalculatorshoulddothetrick.
Togetthetotalamount,gotothePythonShellandtypetotal:
>>>total
83.78760000000001
Nowyouhavethebillamount:83.78760000000001
Ifyou’reusingthelinecommandwindow,youcansimplyentertheabovecodeonaperlinebasis.
ThissimpleprogramshowshowstraightforwardPythonprogrammingisandhowusefulitcouldbeinautomatingtasks.Nexttimeyoueatout,youcanreusetheprogrambysimplychangingthefiguresonyourbillcalculator.Thinkforwardandvisualizehowconvenientit couldbe if you couldput your code in a bigger program thatwill simply askyou toinputthebillamountinsteadofaccessingtheoriginalcode.YoucandothatwithPython.
AssignmentOperators
Theseoperatorsareusefulwhenassigningvaluestovariables:
Operators Function
![Page 45: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/45.jpg)
= assignsthevalueoftherightoperandtotheleftoperand
+=addandaddsthevalueoftherightandleftoperandandassignsthetotaltotheleftoperand
-=subtractand
deductsthevalueoftherightoperandfromthevalueoftheleftoperandandassignsthenewvaluetotheleftoperand
*=multiplyand
multipliestheleftandrightoperandandassignstheproducttotheleftoperand
/=divideand
dividestheleftoperandwiththevalueoftherightoperandandassignsthequotienttotheleftoperand
**=exponent
performsexponentialoperationontheleftoperandandassignstheresulttotheleftoperand
//=floordivisionand
performsfloordivisionontheleftoperandandassignstheresulttotheleftoperand
=Operator
Youhaveseenthisoperatoratworkinpreviouschapterswhenyouhaveassigneddifferentvaluestovariables.Examples:
a=c
a=b+c
a=8
a=8+6
s=“IlovePython.”
+=addand
The‘addand’(+=)operatorissimplyanotherwaytoexpressx=x+asothatyou’llendupwiththestatementx+=a.
![Page 46: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/46.jpg)
-=subtractand
The‘subtractand’(-=)operatorisequivalenttotheexpressionx=x–aandisexpressedwiththestatementx-=a
*=multiplyand
The ‘multiply and’ (*=) operator is the equivalent of the statement x = x * a and isexpressedwithx*=a.
/=divideand
The‘divideand’(/=)operator is likesayingx=x/aandisexpressedwiththestatementx/=a.
%=modulusand
The‘modulusand’ (%=)operator isanotherway tosayx=x%awhereyou’llendupinsteadwiththeexpressionx%=a.
//=floordivisionand
The‘floordivisionand’isequivalenttotheexpressionx=x//aandtakestheformx//=a.
RelationalorComparisonOperators
Relationaloperatorsevaluatevalueson the leftandrightsideof theoperatorandreturntherelationaseitherTrueorFalse.
HerearetherelationaloperatorsinPython:
![Page 47: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/47.jpg)
Operator Meaning
== isequalto
< islessthan
> isgreaterthan
<= islessthanorequalto
>= isgreaterthanorequalto
!= isnotequalto
Examples:
>>>8==6+2
True
>>>6!=6
False
>>>-1>0
False
>>>7>=5
True
LogicalOperators
Pythonsupports3logicaloperators:
or
![Page 48: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/48.jpg)
and
not
xoryIfthefirstargument,x,isfalse,thenitevaluatesthesecondargument,y.Else,itevaluatesx.
xandyIfxisfalse,thenitevaluatesx.Else,ifxistrue,itevaluatesy.
notxIfxisfalse,thenitreturnsTrue.Ifxistrue,itreturnsFalse.
Examples:
>>>(8>9)and(2<9)
False
>>>(2>1)and(2>9)
False
>>>(2==2)or(9<20)
True
>>>(3!=3)or(9>20)
False
>>>not(8>2)
False
>>>not(2>10)
True
![Page 49: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/49.jpg)
PrecedenceofPythonOperators
Pythonoperatorsareevaluatedaccordingtoasetorderorpriority:
Description Operators
1 Exponentiation **
2Ccomplement,unaryplus,andminus
~,+,-
3Multiplication,division,modulo,andfloordivision
*,/,%,//
4 additionandsubtraction +-
5 Rightandleftbitwiseshift >>,<<
6 Bitwise‘AND’ &
7Regular`OR’andBitwiseexclusive‘OR’
|,^
8 Comparisonoperators <=<>>=
9 Equalityoperators ==!=
10 Assignmentoperators =,+=,-=,*-,/=,%=//=**=
11 Identityoperators is,isnot
12 Membershipoperators in,notin
13 Logicaloperators or,and,not
![Page 50: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/50.jpg)
Chapter7Python’sBuilt-inFunctions
Functionsprovideefficiencyandstructuretoaprogramminglanguage.Pythonhasmanyusefulbuilt-infunctionstomakeprogrammingeasier,faster,andmorepowerful.
Theinput()Function
Programs usually require input that can come from different sources: keyboard,mouseclicks, database, another computer’s storage, or the internet. Since the keyboard is themost commonway to gather input, Python provided its users the input() function.Thisfunctionhasanoptionalparametercalledthepromptstring.
Oncetheinputfunctioniscalled,thepromptstringwillbedisplayedonthescreenandtheprogramflowstopsuntil theuserhasenteredaninput.Theinputis theninterpretedandtheinput()functionreturnstheuser’sinputasastring.
Toillustrate,hereisasampleprogramthatcollectskeyboardinputfornameandage:
name=input(“MayIknowyourname?“)
print(“It’sapleasuretomeetyou”+name+“!”)
age=input(“Yourage,please?“)
print(“So,you’re”+age+”yearsold,”+name+“!”)
Beforeyousavethecode,takeacloselookatthestringtobeprintedonthesecondline.You’llnoticethatthereisablankspaceafter‘you’andbeforethedoublequote.Thisspaceensures that there will be a space between ‘you’ and the ‘name’ input when the printcommand is executed. The same convention can be seen on the 4th line with the printcommandwhere‘you’re’isseparatedbyasinglespacefromthe‘age’inputand‘old’isseparatedbyaspacefromthe‘name’input.
Savethecodeasinfo_input.pyandrunit.
![Page 51: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/51.jpg)
ThePythonShellwilldisplaythestringonthefirstline:
MayIknowyourname?
Aresponseisneededatthispointandtheprogramstopsexecutinguntilakeywordinputisobtained.Let’stypeandenterthenameJefftoseewhathappens:
It’sapleasuretomeetyouJeff!
Yourage,please?
Theprogramhasnowproceededtothenextinputfunctionandiswaitingforthekeyboardinput.Let’senter22asJeff’sageandseewhattheprogramdoesnext:
So,you’re22yearsold,Jeff!
![Page 52: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/52.jpg)
The program printed the last string on the program after a keyboard response wasobtained.HereistheentireoutputonthePythonShell:
MayIknowyourname?Jeff
It’sapleasuretomeetyouJeff!
Yourage,please?22
So,you’re22yearsold,Jeff!
Therange()function
Pythonhasamoreefficientwaytohandleaseriesofnumbersandarithmeticprogressionsandthis isbyusingoneitsbuilt-infunctions:range().Therangefunctionisparticularlyusefulin‘forloops’.
Hereisanexampleoftherange()function:
>>>range(5)
range(0,5)
Theexpressionrange(5)abovegeneratesaniteratorthatprogressesintegersfromzeroandendswith4(5-1).Toshowthelistofnumbers,youcanusethecommandlist(range(n)):
![Page 53: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/53.jpg)
>>>list(range(5))
[0,1,2,3,4]
Youcanexercisemorecontroloverthelistoutputbycallingtherange()functionwithtwoarguments:
range(begin,end)
Example:
>>>range(5,9)
range(5,9)
Toshowthelist:
>>>list(range(5,9))
[5,6,7,8]
Theaboveexamplesofrange()demonstratedanincrementof1.YoucanchangethewayPython increments the number by introducing a third argument, the ‘step’. It can be anegativeorpositivenumber,butneverzero.
Hereistheformat:
range(begin,end,step)
Example:
>>>range(10,71,5)
range(10,71,5)
![Page 54: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/54.jpg)
Invokinglist,we’llseethissequenceofnumbers:
>>>list(range(10,71,5))
[10,15,20,25,30,35,40,45,50,55,60,65,70]
Theprint()Function
Python3turnedprintfromastatementintoafunction.Hence,youmustalwaysencloseyourprintparameterswithintheroundparentheses.
Examples:
print(“ThisisPython3printfunction)
print(s)
print(5)
Theprint()functioncanprintanynumberofvalueswithintheparentheses;theymustbeseparatedbycommas.Forexample:
a=3.14
b=“age”
c=32
print(“a=“,a,b,c)
Theresult:
a=3.14age32
![Page 55: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/55.jpg)
ThePythonshelldisplayedvalueswithblankspacesbetweenthem.
abs()
Theabs()functionreturnstheabsolutevalueofasinglenumber.Ittakesanintegerorfloatnumberasargumentandalwaysreturnsapositivevalue.
Examples:
>>>abs(-10)
10
>>>abs(5)
10
Whencomplexnumbersareusedasargument,theabs()functionreturnsitsmagnitude:
>>>abs(3+4j)
5.0
max()
Themax()functiontakestwoormoreargumentsandreturnsthelargestone.
Examples:
>>>max(9,12,6,15)
15
>>>max(-2,-7,-35,-4)
-2
![Page 56: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/56.jpg)
min()
Themin()functiontakestwoormoreargumentsandreturnsthesmallestitem.
Examples:
>>>min(23,-109,5,2)
-109
>>>min(7,26,0,4)
0
type()
Thetype()functionreturnsthedatatypeofthegivenargument.
Examples:
>>>type(“Thisisastring”)
<class‘str’>
>>>type(12)
<class‘int’>
>>>type(2+3j)
<class‘complex’>
>>>type(215.65)
<class‘float’>
![Page 57: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/57.jpg)
len()
Thelen()functionreturnsthelengthofanobjectorthenumberofitemsinalistgivenasargument.
Examples:
>>>len(“pneumonoultramicroscopicsilicovolcanoconiosi”)
44
>>>s=(“winter”,“spring”,“summer”,“fall”)
>>>len(s)
4
HereisalistofPhyton’sbuilt-infunctions:
abs() all() any()
ascii() bin() bool()
bytearray() bytes() callable()
chr() classmethod() compile()
complex() delattr() dict()
dir() divmod() enumerate()
eval() exec() filter()
![Page 58: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/58.jpg)
float() format() frozenset()
getattr() globals() hasattr()
hash() help() hex()
id() __import__() input()
int() isinstance() issubclass()
iter() len() list()
locals() map() max()
memoryview() min() next()
object() oct() open()
ord() pow() print()
property() range() repr()
reversed() round() set()
setattr() slice() sorted()
staticmethod() str() sum()
super() tuple() type()
vars() zip()
![Page 59: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/59.jpg)
Chapter8ConditionalStatements
Conditionalstatementsarecommonamongprogramminglanguagesandtheyareusedtoperformactionsorcalculationsbasedonwhetheraconditionisevaluatedastrueorfalse.If-then-else statements or conditional expressions are essential features of programminglanguagesandtheymakeprogramsmoreusefultousers.
Theif-then-elsestatementinPythonhasthefollowingbasicstructure:
ifcondition1:
block1_statement
elifcondition2:
block2_statament
else:
block3_statement
Thisstructurewillbeevaluatedas:
If condition1 is True, Python will execute block1_statement. If condition1 is False,condition2willbeexecuted.Ifcondition2isevaluatedasTrue,block2_statementwillbeexecuted.Ifcondition2turnsouttobeFalse,Pythonwillexecuteblock3_statement.
Toillustrate,hereisanif-then-elsestatementbuiltwithinthefunction‘your_choice’:
defyour_choice(answer):
ifanswer>5:
print(“Youareoveraged.”)
elifanswer<=5andanswer>1:
print(“WelcometotheToddler’sClub!”)
else:
![Page 60: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/60.jpg)
print(“YouaretooyoungforToddler’sClub.”)
print(your_choice(6))
print(your_choice(3))
print(your_choice(1))
print(your_choice(0))
YouwillgetthisoutputonthePythonShell:
Youareoveraged.
None
WelcometotheToddler’sClub!
None
YouaretooyoungforToddler’sClub.
None
YouaretooyoungforToddler’sClub.
None
Conditionalconstructsmaybranchout tomultiple‘elif’branchesbutcanonlyhaveone‘else’branchattheend.Usingthesamecodeblock,anotherelifstatementmaybeinsertedtoprovideforprivilegedmemberoftheToddler’sclub:2year-oldkids.
defyour_choice(answer):
ifanswer>5:
print(“Youareoveraged.”)
elifanswer<=5andanswer>2:
print(“WelcometotheToddler’sClub!”)
elifanswer==2:
print(“Welcome!YouareastarmemberoftheToddler’sClub!”)
else:
print(“YouaretooyoungforToddler’sClub.”)
print(your_choice(6))
![Page 61: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/61.jpg)
print(your_choice(3))
print(your_choice(1))
print(your_choice(0))
print(your_choice(2))
Youareoveraged.
None
WelcometotheToddler’sClub!
None
YouaretooyoungforToddler’sClub.
None
YouaretooyoungforToddler’sClub.
None
Welcome!YouareastarmemberoftheToddler’sClub!
None
![Page 62: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/62.jpg)
Chapter9Loops
A loop is a programming construct that enables repetitive processing of a sequence ofstatements.Pythonprovidestwotypesofloopstoitsusers:the‘forloop’andthe‘whileloop’.The‘for’and‘while’loopsareiterationstatementsthatallowablockofcode(thebodyoftheloop)toberepeatedanumberoftimes.
TheForLoop
Pythonimplementsaniterator-based‘forloop’.Itisatypeof‘forloop’thatiteratesoveralistofitemsthroughanexplicitorimplicititerator.
Theloopisintroducedbythekeyword‘for’whichisfollowedbyarandomvariablenamewhichwillcontainthevaluessuppliedbytheobject.
ThisisthesyntaxofPython’s‘forloop’:
forvariableinlist:
statements
else:
statements
Hereisanexampleofa‘forloop’inPython:
pizza = [“NewYork Style Pizza”, “Pan Pizza”, “Thin n Crispy Pizza”, “Stuffed CrustPizza”]
forchoiceinpizza:
ifchoice==“PanPizza”:
print(“Pleasepay$16.Thankyou!”)
print(“Delicious,cheesy”+choice)
![Page 63: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/63.jpg)
else:
print(“Cheesypanpizzaismyall-timefavorite!”)
print(“Finally,I’mfull!”)
Runthisandyou’llgetthefollowingoutputonPythonShell:
Delicious,cheesyNewYorkStylePizza
Pleasepay$16.Thankyou!
Delicious,cheesyPanPizza
Delicious,cheesyThinnCrispyPizza
Delicious,cheesyStuffedCrustPizza
Cheesypanpizzaismyall-timefavorite!
Finally,I’mfull!
Usingabreakstatement
A Python break statement ends the present loop and instructs the interpreter to startsexecutingthenextstatementaftertheloop.Itcanbeusedinboth‘for’and‘while’loops.Besides leading the program to the statement after the loop, a break statement alsopreventstheexecutionofthe‘else’statement.
To illustrate, a break statement may be placed right after the print function of the ‘ifstatement’:
pizza = [“NewYork Style Pizza”, “Pan Pizza”, “Thin n Crispy Pizza”, “Stuffed CrustPizza”]
forchoiceinpizza:
ifchoice==“PanPizza”:
print(“Pleasepay$16.Thankyou!”)
break
print(“Delicious,cheezy”+choice)
else:
![Page 64: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/64.jpg)
print(“Cheezypanpizzaismyall-timefavorite!”)
print(“Finally,I’mfull!”)
ThePythonShellwillnowshow:
Delicious,cheezyNewYorkStylePizza
Pleasepay$16.Thankyou!
Finally,I’mfull!
UsingContinueStatement
Thecontinuestatementbringsbackprogramcontroltothestartoftheloop.Youcanuseitforboth‘for’and‘while’loops.
Toillustrate,thecontinuestatementmaybeplacedrightaftertheprintfunctionofthe‘forloop’toreplacethebreakstatement:
pizza = [“NewYork Style Pizza”, “Pan Pizza”, “Thin n Crispy Pizza”, “Stuffed CrustPizza”]
forchoiceinpizza:
ifchoice==“PanPizza”:
print(“Pleasepay$16.Thankyou!”)
continue
print(“Delicious,cheesy”+choice)
else:
print(“Cheesypanpizzaismyall-timefavorite!”)
print(“Finally,I’mfull!”)
Theoutputwillbe:
![Page 65: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/65.jpg)
Delicious,cheesyNewYorkStylePizza
Pleasepay$16.Thankyou!
Delicious,cheesyThinnCrispyPizza
Delicious,cheesyStuffedCrustPizza
Cheesypanpizzaismyall-timefavorite!
Finally,I’mfull!
Usingtherange()FunctionwiththeforLoop
Therange()functioncanbecombinedwiththe‘forloop’tosupplythenumbersrequiredby the loop. In the following example, the range(1, x+1)provided thenumbers1 to50neededbythe‘forloop’toaddthesumof1until50:
x=50
total=0
fornumberinrange(1,x+1):
total=total+number
print(“Sumof1until%d:%d”%(x,total))
ThePythonShellwilldisplay:
l.py
Sumof1until50:1275
TheWhileLoop
APython‘whileloop’repeatedlycarriesoutatargetstatementwhiletheconditionistrue.
![Page 66: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/66.jpg)
The loop iteratesas longas thedefinedcondition is true.When itceases tobe trueandbecomesfalse,controlpassestothefirstlineaftertheloop.
The‘whileloop’hasthefollowingsyntax:
whilecondition
statement
statement
Hereisasimple‘whileloop’:
counter=0
while(counter<10):
print(‘Thecountis:’,counter)
counter=counter+1
print(“Done!”)
Ifyourunthecode,youshouldseethisoutput:
l.py
Thecountis:0
Thecountis:1
Thecountis:2
Thecountis:3
Thecountis:4
Thecountis:5
Thecountis:6
Thecountis:7
Thecountis:8
Thecountis:9
Done!
![Page 67: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/67.jpg)
UsingPassStatement
The pass statement tells the Python interpreter to ‘do nothing’. The interpreter simplycontinueswiththeprogram’sexecutionwheneverthepassstatementisencountered.ThisattributemakesitagoodplaceholderwheneverPythonsyntacticallyrequiresalinebuttheprogram itself does not require action. It can be very useful when you’re creating aprogramandyouneedtofocusonspecificareasofyourcode,butyoustillwanttoreservesomeloopsortestruntheincompletecode.
Hereishowyouwoulduseapassstatementtofillgapswithinacode:
deffunction_name(x):
pass
Chapter10User-DefinedFunctions
A function is a set of statements that perform a specific task, a common structuringelementthatallowsyoutouseapieceofcoderepeatedlyindifferentpartsofaprogram.The use of functions improve a program’s clarity and comprehensibility and makesprogrammingmore efficient by reducing code duplication and breaking down complextasks intomoremanageable pieces. Functions are also known as routines, subroutines,methods,procedures,orsubprograms.
Theycanbepassedasarguments,assignedtovariables,orstoredincollections.
Auser-definedPythonfunctioniscreatedordefinedbythedefstatementandfollowsthesyntax:
deffunction_name(parameterlist):
![Page 68: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/68.jpg)
functionbody/statements
The indented statementsmake up the body of the function and are executedwhen thefunction iscalled.Once thefunction iscalled,parameters insideroundbracketsbecomearguments.
Functionbodiescanhavemorethanonereturnstatementwhichmaybeplacedanywherewithinthefunctionblock.Returnstatementsendthefunctioncallandreturnthevalueoftheexpressionafterthereturnkeyword.Areturnstatementwithnoexpressionreturnsthespecialvalue ‘None’. In theabsenceof a return statementwithin the functionbody, theendofthefunctionisindicatedbythereturnofthevalue‘None’.
The docstring is an optional statement after the function title which explains what thefunction does.While it is notmandatory, documenting your codewith a docstring is agoodprogrammingpractice.
HereisasimplefunctionthatprintsIlovePizza!
deflove_pizza():
print“IlovePizza!”
Hereisafunctionwithaparameterandreturnkeyword:
defabsolute_value(number):
ifnumber>=0:
returnnumber
else:
return-number
print(absolute_value(3))
print(absolute_value(-5))
![Page 69: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/69.jpg)
Intheaboveexample,numberistheparameterofthefunctionabsolute_value.Itactsasavariablenameandholdsthevalueofapassedinargument.
Hereistheoutputwhentheabovecodeisrun:
3
5
Followingisafunctionwithanif-then-elsestatement.
defshutdown(yn):
ifyn.lower()==“y”:
return(“Closingfilesandshuttingdown”)
elifyn.lower()==(“n”):
return(“Shutdowncancelled”)
else:
return(“Pleasecheckyourresponse.”)
print(shutdown(“y”))
print(shutdown(“n”))
print(shutdown(“x”))
PythonShellwilldisplay:
Closingfilesandshuttingdown
Shutdowncancelled
Pleasecheckyourresponse.
Functioncantakemorethanoneparameterandusethemforcomputations:
![Page 70: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/70.jpg)
defcalculator(x,y):
returnx*y+2
print(calculator(2,6))
print(calculator(3,7))
Runthecodeandyou’llgettheoutput:
14
23
Functionscancallotherfunctions
Functionscanperformdifferenttypesofactionssuchasdosimplecalculationsandprinttext.Theycanalsocallanotherfunction.
Forexample:
defmembers_total(n):
returnn*3
deforg_total(m):
returnmembers_total(m)+5
Toseewhatyoucodedoes,enterthefollowingprintcommands:
print(org_total(2))
print(org_total(5))
print(org_total(10))
You’llgettheseresults:
![Page 71: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/71.jpg)
11
20
35
Scopeandlifetimeofalocalvariable
A variable’s scope refers to a program’s sectionswhere it is recognized. Variables andparametersdefinedwithinafunctionhavealocalscopeandarenotvisiblefromoutsideofthefunction.Ontheotherhand,avariable’slifetimereferstoitsperiodofexistenceinthememory. Its lifetime coincides with the execution of a function which ends when youreturnfromthefunction.Avariable’svalueisdiscardedoncethereturnisreachedandafunctionwon’tbeabletorecallavariable’svaluefromitspreviousvalue.
![Page 72: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/72.jpg)
Chapter11ClassesandObject-OrientedProgramming
Pythonisanobject-orientedprogramminglanguage,whichmeansthatitmanipulatesandworkswithdatastructurescalledobjects.ObjectscanbeanythingthatcouldbenamedinPython – integers, functions, floats, strings, classes, methods, etc. These objects haveequalstatusinPython.Theycanbeusedanywhereanobjectisrequired.Youcanassignthem to variables, lists, or dictionaries. They can also be passed as arguments. EveryPythonobject is a class.Aclass is simplyawayoforganizing,managing, andcreatingobjectswiththesameattributesandmethods.
In Python, you can define your own classes, inherit from your own defined classes orbuilt-inclasses,andinstantiatethedefinedclasses.
ClassSyntax
Todefineaclass,youcanuse‘class’,areservedkeyword,followedbytheclassnameandacolon.Byconvention,allclassesstartinuppercase.Forexample:
classStudents:
pass
Tocreateaclassthattakesanobject:
classStudents(object)
The__init__()method
Immediately after creating an instance of the class, you have to call the __init__()function.Thisfunctioninitializestheobjectsitcreates.Ittakesatleasttheargument‘self’,aPythonconvention,whichgivesidentitytotheobjectbeingcreated.
![Page 73: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/73.jpg)
Examples:
classStudents:
def__init__(self):
classEmployees(object):
def__init__(self,name,rate,hours):
Afunctionusedinaclassiscalledamethod.Hence,the__init__()functionisamethodwhenitisusedtoinitializeclasses.
InstanceVariables
When you add more arguments to the def_init_() besides the self, you’ll need to addinstance variables so that any instance object of the class will be associated with theinstanceyoucreate.
Forexample:
classEmployees(object):
def__init__(self,name,rate,hours):
name.self=name
rate.self=rate
hours.self=hours
Intheaboveexample,name.self,rate.self,andhours.selfaretheinstancevariables.
WhenyoucreateinstancesoftheclassEmployees,eachmemberwillhaveaccesstothevariableswhichwereinitializedthroughthe__init__method.Toillustrate,youcancreateor‘instantiate’newmembersoftheclassEmployees:
staff=Employees(“Wayne”,20,8)
![Page 74: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/74.jpg)
supervisor=Employees(“Dwight”,35,8)
manager=Employees(“Melinda”,100,8)
YoucanthenusetheprintcommandtoseehowtheinstancevariablesinteractedwiththemembersoftheclassEmployees:
print(staff.name,staff.rate,staff.hours)
print(supervisor.name,supervisor.rate,supervisor.hours)
print(manager.name,manager.rate,manager.hours)
ThePythonShellwilldisplaythisoutput:
Wayne208
Dwight358
Melinda1008
Hereishowtheentirecodewaswrittenontheeditor/filewindow:
Filewindow:employees.py
![Page 75: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/75.jpg)
Here’stheoutput:
Inheritance
InheritanceisaPythonprocessthatallowsoneclasstotakeonthemethodsandattributesof another. This feature allows users to create more complicated classes that inheritmethods or variables from their parent or base classes and makes programming moreefficient.
Thisisthesyntaxfordefiningaclassthatinheritsallvariablesandfunctionfromaparentclass:
classChildClass(ParentClass):
Toillustrate,youcancreateanewclass,Resigned, thatwill inheritfromtheEmployeesclassandtakeanadditionalvariable,status:
![Page 76: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/76.jpg)
classEmployees(object):
def__init__(self,name,rate,hours):
self.name=name
self.rate=rate
self.hours=hours
staff=Employees(“Wayne”,20,8)
supervisor=Employees(“Dwight”,35,8)
manager=Employees(“Melinda”,100,8)
print(staff.name,staff.rate,staff.hours)
print(supervisor.name,supervisor.rate,supervisor.hours)
print(manager.name,manager.rate,manager.hours)
classResigned(Employees):
def__init__(self,name,rate,hours,status):
self.name=name
self.rate=rate
self.hours=hours
self.status=status
exemp_1=Resigned(“Dorothy”,32,8,“retired”)
exemp_2=Resigned(“Malcolm”,48,8,“resigned”)
print(exemp_1.name,exemp_1.rate,exemp_1.hours,exemp_1.status)
print(exemp_2.name,exemp_2.rate,exemp_2.hours,exemp_2.status)
![Page 77: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/77.jpg)
HereistheoutputonthePythonShellwhenthecodeisexecuted;
![Page 78: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/78.jpg)
![Page 79: Python: The Ultimate Beginner's Guide! - Andrew Johansen.pdf · Introduction I want to thank you and congratulate you for purchasing this book… “Python: The Ultimate Beginner’s](https://reader030.vdocuments.us/reader030/viewer/2022041001/5ea192e6de3d353542559d2c/html5/thumbnails/79.jpg)
Conclusion
Congratulationsforfinishingthisbook,IhopeitwasabletoequipyouwiththeessentialskillsandfundamentalknowledgetoexploreandharnessthepowerfulfeaturesofPythonasaprogramming language.By the timeyou finished reading thebook, I amconfidentthatyouwillbepreparedtoputyourbasicprogrammingknowledgetopracticaleverydayuses.
The next step is to take up advanced Python programming courses that will help youcreatemorecomplexprogramssuchasgames,webapplications,andproductivitytools.
Finally, ifyouenjoyedthisbook,pleasetakethetimetoshareyourthoughtsandpostapositivereviewonAmazon.It’dbegreatlyappreciated!
Thankyouandgoodluck!