The python book 1st edition rob mastrodomenico all chapter instant download

Page 1


https://ebookmass.com/product/the-python-book-1st-editionrob-mastrodomenico/

Instant digital products (PDF, ePub, MOBI) ready for you

Download now and discover formats that fit your needs...

The Python Book 5th Edition Dan Peel

https://ebookmass.com/product/the-python-book-5th-edition-dan-peel/

ebookmass.com

The Introverted Actor: Practical Approaches 1st ed. Edition Rob Roznowski

https://ebookmass.com/product/the-introverted-actor-practicalapproaches-1st-ed-edition-rob-roznowski/

ebookmass.com

Pearson Edexcel International GCSE (9-1) Economics Student Book 1st Edition Rob Jones

https://ebookmass.com/product/pearson-edexcel-internationalgcse-9-1-economics-student-book-1st-edition-rob-jones/ ebookmass.com

The Rhymer's Daughter (Leopard's Bane Book 2) Phill Featherstone

https://ebookmass.com/product/the-rhymers-daughter-leopards-banebook-2-phill-featherstone/

ebookmass.com

Christmas Cookies With Daddy: An MM Age Play Holiday & Hockey Romance (Deadly Puck Daddies Book 3) Zack Wish

https://ebookmass.com/product/christmas-cookies-with-daddy-an-mm-ageplay-holiday-hockey-romance-deadly-puck-daddies-book-3-zack-wish/

ebookmass.com

(eTextbook PDF) for Chemistry in Context 8th Edition by American

https://ebookmass.com/product/etextbook-pdf-for-chemistry-incontext-8th-edition-by-american/

ebookmass.com

Divine Style: Walt Whitman and the King James Bible. 1st Edition F. W. Dobbs-Allsopp.

https://ebookmass.com/product/divine-style-walt-whitman-and-the-kingjames-bible-1st-edition-f-w-dobbs-allsopp/

ebookmass.com

A Murder of Crows: Mafia University #1 Evelyn Flood

https://ebookmass.com/product/a-murder-of-crows-mafiauniversity-1-evelyn-flood/

ebookmass.com

Un espía privado: Las cartas de John le Carré John Le Carré

https://ebookmass.com/product/un-espia-privado-las-cartas-de-john-lecarre-john-le-carre/

ebookmass.com

Nelson English: Year 2/Primary 3: Pupil Book 2 Wendy Lindsay

https://ebookmass.com/product/nelson-english-year-2-primary-3-pupilbook-2-wendy-lindsay/

ebookmass.com

ThePythonBook

ThePythonBook

RobMastrodomenico

GlobalSportsStatistics

Swindon,UnitedKingdom

Thiseditionfirstpublished2022 ©2022JohnWileyandSonsLtd

Allrightsreserved.Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,or transmitted,inanyformorbyanymeans,electronic,mechanical,photocopying,recordingorotherwise, exceptaspermittedbylaw.Adviceonhowtoobtainpermissiontoreusematerialfromthistitleisavailable athttp://www.wiley.com/go/permissions.

TherightofRobMastrodomenicotobeidentifiedastheauthorsofthisworkhasbeenassertedin accordancewithlaw.

RegisteredOffice

JohnWiley&Sons,Inc.,111RiverStreet,Hoboken,NJ07030,USA

JohnWiley&SonsLtd,TheAtrium,SouthernGate,Chichester,WestSussex,PO198SQ,UK

EditorialOffice

9600GarsingtonRoad,Oxford,OX42DQ,UK

Fordetailsofourglobaleditorialoffices,customerservices,andmoreinformationaboutWileyproducts visitusatwww.wiley.com.

Wileyalsopublishesitsbooksinavarietyofelectronicformatsandbyprint-on-demand.Somecontentthat appearsinstandardprintversionsofthisbookmaynotbeavailableinotherformats.

LimitofLiability/DisclaimerofWarranty

Thecontentsofthisworkareintendedtofurthergeneralscientificresearch,understanding,anddiscussion onlyandarenotintendedandshouldnotberelieduponasrecommendingorpromotingscientificmethod, diagnosis,ortreatmentbyphysiciansforanyparticularpatient.Inviewofongoingresearch,equipment modifications,changesingovernmentalregulations,andtheconstantflowofinformationrelatingtothe useofmedicines,equipment,anddevices,thereaderisurgedtoreviewandevaluatetheinformation providedinthepackageinsertorinstructionsforeachmedicine,equipment,ordevicefor,amongother things,anychangesintheinstructionsorindicationofusageandforaddedwarningsandprecautions. Whilethepublisherandauthorshaveusedtheirbesteffortsinpreparingthiswork,theymakeno representationsorwarrantieswithrespecttotheaccuracyorcompletenessofthecontentsofthisworkand specificallydisclaimallwarranties,includingwithoutlimitationanyimpliedwarrantiesofmerchantability orfitnessforaparticularpurpose.Nowarrantymaybecreatedorextendedbysalesrepresentatives,written salesmaterialsorpromotionalstatementsforthiswork.Thefactthatanorganization,website,orproduct isreferredtointhisworkasacitationand/orpotentialsourceoffurtherinformationdoesnotmeanthat thepublisherandauthorsendorsetheinformationorservicestheorganization,website,orproductmay provideorrecommendationsitmaymake.Thisworkissoldwiththeunderstandingthatthepublisheris notengagedinrenderingprofessionalservices.Theadviceandstrategiescontainedhereinmaynotbe suitableforyoursituation.Youshouldconsultwithaspecialistwhereappropriate.Further,readersshould beawarethatwebsiteslistedinthisworkmayhavechangedordisappearedbetweenwhenthisworkwas writtenandwhenitisread.Neitherthepublishernorauthorsshallbeliableforanylossofprofitorany othercommercialdamages,includingbutnotlimitedtospecial,incidental,consequential,orother damages.

LibraryofCongressCataloging-in-PublicationData

Names:Mastrodomenico,Rob,author.

Title:ThePythonbook/RobMastrodomenico.

Description:Hoboken,NJ:Wiley,2022.|Includesbibliographical referencesandindex.

Identifiers:LCCN2021040056(print)|LCCN2021040057(ebook)|ISBN 9781119573319(paperback)|ISBN9781119573395(adobepdf)|ISBN 9781119573289(epub)

Subjects:LCSH:Python(Computerprogramlanguage)

Classification:LCCQA76.73.P98M3792022(print)|LCCQA76.73.P98 (ebook)|DDC005.13/3–dc23

LCrecordavailableathttps://lccn.loc.gov/2021040056

LCebookrecordavailableathttps://lccn.loc.gov/2021040057

CoverDesign:Wiley

CoverImage:©shuoshu/GettyImages

Setin9.5/12.5ptSTIXTwoTextbyStraive,Chennai,India

10987654321

16Pandas 103

16.1NumpyArrays 103

16.2Series 106

16.3DataFrames 111

16.4Merge,Join,andConcatenation 121

16.5DataFrameMethods 136

16.6MissingData 141

16.7Grouping 146

16.8ReadinginFileswithPandas 154

17Plotting 159

17.1Pandas 159

17.2Matplotlib 169

17.3Seaborn 179

18APIsinPython 215

19WebScrapinginPython 229

19.1AnIntroductiontoHTML 229

19.2WebScraping 233

20Conclusion 255 Index 257

Introduction

Welcometo ThePythonBook,overthefollowingpagesyouwillbegivenaninsightinto thePythonlanguage.Thegenesisofthisbookhascomefrommyexperienceofusingand moreimportantlyteachingPythonoverthelast10years.WithmybackgroundasaData Scientist,Ihaveusedanumberofdifferentprogramminglanguagesoverthecourseofmy careerandPythonbeingtheonethathasstuckwithme.WhyPython?FormeIenjoy Pythonbecauseitsfasttodevelopwithandcoversmanydifferentapplicationallowingmeto usePythonforprettymucheverything.Howeverforyouthereader,Pythonisagreatchoice oflanguagetolearnasitseasytopickupandfasttogetgoingwithwhichmeansthatforthe noviceprogrammerstheycanfeelliketheyaremakingprogress.Thisbookisnotjustfor completenovices,ifyouhavesomeexperiencewithPython,thenthisbookisagreatreference.ThefactthatyoucanpickupPythonquicklymeansthatmanyusersskipthebasics. Thisbooklookstocoverallthebasicsgivingyouthebuildingblockstodogreatthingswith thelanguage.Whatthisbookisnotintendedtodoisovercomplicatinganything.Python isbeautifulinitssimplicityandthisbooklookstosticktothatapproach.Conceptswillbe explainedinsimpletermsandexampleswillbeusedtoshowhowtopracticallyusethe introducedconcepts.

Nowhavingdiscussedwhatthisbookisintendedtodo,whatisPython?Simplyput Pythonisaprogramminglanguage,itsgeneralpurposemeaningthatitcandolotsofthings. Inthisbook,wewillspecialiseinapplyingPythontodata-drivenapplications,however PythoncanbeusedformanyotherapplicationsincludingAI,machinelearning,web development,tonamejustafew.Thelanguageitselfisofhighlevelandalsointerpreted meaningthatcodeneednotbecompiledbeforerunning.Oneofthebigattractionstothe languageisthesimplicityofitssyntax,whichmakesitgreattolearnandevenbetterto writecode.Asidefromtheclear,easytounderstandsyntax,thelanguagemakesuseof indentationasanimportanttooltodistinguishdifferentelementsofthecode.Pythonis anobject-orientatedlanguageandwewilldemonstratethisinmoredetailthroughout thisbook.However,youcanwritePythoncodehowyoupreferbeitobjectorientated, functionalorinteractively.ThebestwaytodemonstratePythonisbydoing,solet’sget startedbuttodosoweneedtogetPythoninstalled. ThePythonBook,FirstEdition.RobMastrodomenico. ©2022JohnWiley&SonsLtd.Published2022byJohnWiley&SonsLtd.

GettingStarted

Forthepurposesofthisbook,wewantyoutoinstalltheAnacondadistributionofPython thatisavailableathttps://www.anaconda.com.Here,youhavedistributionsforWindows, Mac,andLinux,whichcanbeeasilyinstalledonyourcomputer.Onceyouhavethe Anacondainstalled,youwillhaveaccesstotheAnacondanavigatorasshownin Figure2.1.

Here,yougetthefollowingincludedbydefault:

● JupyterLab

● Notebook

● QtConsole

● Spyder

TofollowtheexampleswithinthisbookyoucanusetheNotebookorQtConsole. TheNotebookisaninteractivewebbasededitorasshowninFigure2.2.

Here,youcantypeyourcode,runthecommand,andthenseetheresult,whichisanice waytoworkandisverypopular.Here,wewillshowhowwecandefineavariablexand thenjusttypexandrunthecommandwiththerunbuttontoshowtheresult(Figure2.3).

Howeverforthepurposesofthebookwewilluseaconsole-basedviewthatyoucaneasily obtainthroughtheQtConsole.AnexampleisshowninFigure2.4.

Likewiththenotebook,weshowthesameexampleusingQtConsoleinFigure2.5. Withinthisbookwewilldenoteanythingthatisaninputwith >>> andwithanyoutput havingnoarrowsprecedingit(Figure2.6).

Anotherconceptthatthereaderwillneedtobefamiliarwithistheabilitytonavigate usingtheterminal(linuxsystemsincludingmac)orcommandprompt(windows).These canbeobtainedthroughvariousapproachesbutsimplyusingthesearchprocedureswith thewordterminalorcommandpromptwillbringuptherelevantscreen.Tonavigate throughthefilesystemyoucanusethecommandcdtochangedirectory.Thisessentially islikeusclickingonafoldertoseewhatisinit.Unlikeusingafileviewinginterface youcannotseewhatisinagivendirectorybydefaultsotodosoyouneedtousethe commandls.Thiscommandliststhefilesanddirectorieswithinthecurrentlocations.Let’s demonstratewithanexampleofnavigatingtoadirectoryandthenrunningapythonfile. AsidefromtheAnacondanavigatorwehaveover250open-sourcedatascienceand machinelearningpackagesareautomaticallyinstalled.Youcanalsomakeuseofthe condainstallertoinstallover7500packageseasilyintoPython.Afulllistofpackages

ThePythonBook,FirstEdition.RobMastrodomenico. ©2022JohnWiley&SonsLtd.Published2022byJohnWiley&SonsLtd.

Figure2.1 Anacondanavigator.

Figure2.2 JupyterNotebook.

Figure2.3 JupyterNotebookexample.

Figure2.4 QtConsole.

Figure2.5 QtConsoleexample.

Figure2.6 Commandlineexample.

thatcomewithAnacondaisavailablefortherelevantoperatingsystemfromhttps://repo .anaconda.com/pkgs/.Detailsontheusingthecondainstallerisavailablefromhttps:// docs.anaconda.com/anaconda/user-guide/tasks/install-packages/howeverthisisoutside thescopeofthisbook.Thelastconceptwewillraisebutnotcoverindetailisthatofvirtual environments.ThisconceptiswheretheuserdevelopsinanisolatedPythonenvironment andaddspackagesasneeded.Itisaverypopularapproachtodevelopmenthoweveras thisbookisaimedatbeginnersweuseallpackagesincludedintheAnacondainstallation.

PackagesandBuiltinFunctions

Wehavediscussedpackageswithoutreallydescribingwhattheyaresolet’slookatpackages andhowitsitswithinthegeneralsetupofPython.Asmentionedpreviously,Pythonis objectorientatedwhichmeansthateverythingisanobject,you’llgettounderstandthisin practice,howeverthereareafewimportantbuiltinfunctionswhicharen’tobjectsandthey areworthmentioninghereastheywillbeusedwithinthebook.Thesebuiltintypeswillbe usedthroughoutthebooksokeepaneyeoutforthem.Belowweshowsomeusefulones, forafulllistrefertohttps://docs.python.org/3/library/functions.html.

● dir():Thisfunctiontakesinanobjectandreturnsthe_dir_()ofthatobjectgivingusthe attributesoftheobject.

>>> name = 'Rob'

>>> dir(name)

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

● float():Returnsafloatingpointnumberfromanintegerofstring

>>> x = '1'

>>> float(1) 1.0

● int():Returnsanintegerfromafloatofstring

>>> x = '1'

>>> int(1) 1

ThePythonBook,FirstEdition.RobMastrodomenico. ©2022JohnWiley&SonsLtd.Published2022byJohnWiley&SonsLtd.

● len():Returnsthelengthofanobject

>>> name = 'Rob'

>>> len(name)

3

>>> x = [1, 2, 3, 4]

>>> len(x)

4

● list():Createsalistfromtheargumentgiven

>>> name = 'rob'

>>> list(name) ['r', 'o', 'b']

● max():Givesthemaximumvaluefromtheargumentprovided

>>> x = [1, 2, 3, 4]

>>> max(x)

4

>>> name = ['r', 'o', 'b']

>>> max(name) 'r'

● min():Givestheminimumvaluefromtheargumentprovided

>>> x = [1, 2, 3, 4]

>>> min(x)

1

>>> name = ['r', 'o', 'b']

>>> min(name) 'b'

● print():Printstheobjecttothetextstream

>>> x = [1, 2, 3, 4]

>>> print(x) [1, 2, 3, 4]

● round():Roundsthenumbertoaspecifiedprecision

>>> y =1.387668

>>> round(y,2) 1.39

● str():Convertstheobjecttotypestring

>>> y =1.387668

>>> str(y) '1.387668'

● type():Returnsthetypeofanobject

>>> y =1.387668

>>> type(y)

<class ' float'>

● abs():Returnstheabsolutevalueofanumericvaluepassedin

>>> z =-0.657

>>> abs(z)

0.657

● help():GivesaccesstothePythonhelpsystem

>>> help(list)

Helpon class list in modulebuiltins:

class list(object)

| list(iterable=(), /)

| Built-in mutablesequence

| Ifnoargument is given,theconstructorcreatesanewempty list

| Theargumentmustbeaniterable if specified. |

| Methodsdefinedhere:

| __add__(self,value, /)

| Return self+value.

| __contains__(self,key, /)

| Returnkey in self

| __delitem__(self,key, /)

| Delete self[key].

|

| __eq__(self,value, /)

| Return self==value.

NowifyouareunfamiliarwiththePythontheconceptsusedabovetheywillbeintroducedthroughoutthisbook.

AlongsidethesebuiltinfunctionsPythonalsocomeswithanumberofpackages.These packagesperformspecifictasksandareimportedintoourcode.Pythonhasanumberof packagesthatcomeasdefaulthowevertherearelotsofthird-partypackageswhichwecan alsouse.InusingtheAnacondadistributionwegetallthedefaultpackagesaswellasthe packagesthataredescribedpreviously.Wewillcoverbothdefaultandthird-partypackages throughoutthisbook.Todemonstratethiswewillintroducehowtoimportapackage.The packagewearegoingtointroduceisdatetimewhichispartofthestandardPythonlibrary. WhatthismeansisitcomeswiththePythonandisnotdevelopedbyathirdparty.Nowto importthedatetimepackageyoujustneedtotypethefollowing:

>>> import datetime

Indoingthiswenowhaveaccesstoeverythingwithindatetimeandtoseewhatdatetimecontainswecanrunthebuiltinfunctiondirwhichasweshowedearliergivesusthe attributeoftheobject.

>>> import datetime

>>> dir(datetime) ['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']

Nowifwewanttoseewhattheseattributesareweusethedotsyntaxtoaccessattributes oftheobject.SotoseewhatMINYEARandMAXYEARarewecandosoasfollows.

>>> import datetime

>>> datetime.MAXYEAR

9999

>>> datetime.MINYEAR

1

Nowwecanimportspecificpartsofapackagebyusingthefromsyntaxasdemonstrate below.

>>> from datetime import date

Sowhatthissaysisfromthepackagedatetimeimportthespecificdateattribute.Thisis thentheonlyaspectofdatetimethatwehaveaccessto.Thisisgoodpracticetoonlyimport whatyouneedfromapackage.Noweverytimewewanttousedatewehavetocalldate,in thiscaseitseasyenoughbutyoucanalsogivetheimportanaliaswhichcanreduceyour codedown.

>>> from datetime import date as d

Thatisthebasicsofimportingpackages,throughoutthisbookwewillimportfrom variouspackagesaswellasshowhowthissamesyntaxcanbeusedtoimportourown code.Alongsidebuiltinfunctionsthesearekeyconceptsthatwewilluseextensivelywithin thisbook.

DataTypes

ThenextconceptofPythonthatwewillintroduceisdatatypesandinthischapterwe willintroduceanumberoftheseandshowhowtheybehavewhenappliedtosomebasic operators.Wefirststartbyintroducingintegerswhichareanumberwithoutadecimal point,writtenasfollows:

>>>1 1 >>>2 2

Afloatisbydefinitionafloatingpointnumbersowecanwritethepreviousasfollows:

>>>1.0 1.0

>>>2.0

2.0

Astringissimplysomethingenclosedineitheradoubleorsinglequote.Soagainwecan rewritewhatwehaveseenasfollows:

>>> "2.0" '2.0'

Giventhefactthatweknowhowtodefinethesevariables,howcanwecheckwhatthey are?Well,convenientlyPythonhasatypemethodthatwillallowustodeterminethetype ofavariable.Sowewillrewritewhatwehavedoneandassigneachinstancetoavariable andthenseewhattypePythonthinkstheyare

>>>=1

>>> type(x)

<class "int">

>>> y =1.0

>>> type(y)

<class "float">

>>> z = "1.0"

>>> type(z)

<class "str">

ThePythonBook,FirstEdition.RobMastrodomenico. ©2022JohnWiley&SonsLtd.Published2022byJohnWiley&SonsLtd.

Sonowwecandefinethevariables,thequestioniswhatcanwedowiththem?Initially wewillconsiderthefollowingoperations:

+

/

Thesearecommonlyknownasthemathematicaloperation:addition,subtraction, multiplication,anddivision.

Solet’sstartwith + nowifwehavetwointegersapplying + ismathematicaladditionas wewillshow

>>> x =10

>>> y =16

>>> x + y

Similarlyifwedothesamewithtwofloatswegetasimilarresult

>>> x =10.0

>>> y =16.0

>>> x + y

26.0

Butwhathappensifweapplyadditiontoafloatandaninteger,let’ssee

>>> x =10

>>> y =16.0

>>> z = x + y

>>> z

26.0

>>> type(z)

<class "float">

Whatweseeisthatadditionworksonafloatandanintegerbutitreturnsafloat,soit’s convertingtheintegerintoafloat.

Whatifweuseadditiononastring?Wellthisistheinterestingpart,let’srunthesame examplefrombeforewithxandyasstringrepresentations.

>>> x = "10"

>>> y = "16.0"

>>> z = x + y

>>> z "1016.0"

Whathashappenedhere?Wellwehavestucktogetherxandy,thisisknownasconcatenationandisaverypowerfultoolindealingwithstrings.

Weconsideredthe + operationwithintegersandfloatsbutwhatwillhappenifwedothe + operationwithastringandsayaninteger

>>> x = "10"

>>> y =16

>>> z = x + y

Traceback(mostrecentcalllast):

File "<stdin>",line 1, in <module>

TypeError:mustbe str, not float

Whatweseehereisanerrormessagesayingwecannotconcatenateastrandintobject. SoPythoninthisinstancewantstousethe + operationasconcatenationbutduetothefact itdoesn’thavetwostringsitcan’tdothatandhencethrowsanerror.InPythonyoucannot mixastringandintegerorstringandfloatsowewon’tconsideroperationsbetweenthese typesfortherestofthissection.

Letusnowlookatthe operation.Firstconsideringtwointegerswegetthefollowing:

>>> x =10

>>> y =16

>>> z = x - y

Asyoumayhaveexpectedthe operationwithtwointegersactsasmathematicalsubtraction.Ifweapplyittotwofloats,ortoamixoffloatsandintegersitactsassubtraction. Whataboutforstrings,canweapply totwostrings?

>>> x = "10"

>>> y = "16"

>>> z = x - y

Traceback(mostrecentcalllast):

File "<stdin>",line 1, in <module>

TypeError:unsupportedoperand type(s) for -: 'str' and 'str'

Herewegetanothererrorbutthistimeitisbecausethe operationdoesn’tsupport strings.Whatthismeansisthatwhenyoutrytooperateontwostringsusingthisoperation, itdoesn’tknowwhattodo.Thesameistruefor*and/operationsonstring.So,ifwe aredealingwithstringstheonlyoperationfromthissectionthatwecanuseis + whichis concatenation.

Thenextoperationwewillconsideris*whichisgenerallyknownasmathematical multiplicationtomost.Soconsideringitsuseontwointegerswegetthefollowing:

>>> x =10

>>> y =16

>>> x * y 160

Aswecanseeitsmathematicalmultiplication,thesameistruewhenwerunthesame ontwofloats.Letusseewhathappenswhenwemixfloatsandintegers.

>>> x =10

>>> y =16.0

>>> x * y

160.0

Aswecanseeitreturnsmultiplicationinfloatformat,solikewithadditionandsubtractionitconvertsintegerstofloats.

Next,weneedtoseehow/operationworksonintegersandfloats,sofirstweconsider thesametypes,sowewillapply/onintegers:

>>> x =10

>>> y =16

>>> x / y

0.625

Thereareotherdatatypesbeyondtheseandthefirstweconsiderarecomplexnumbers whichcanbedefinedasfollows

>>> x =3+5j

>>> x (3+5j)

>>> y =5j

>>> y 5j

>>> z =-5j

>>> z (-0-5j)

Wecanobtaintherealandimaginarypartsofourcomplexnumbersasfollows

>>> x real

3.0

>>> x imag

5.0

>>> y real

0.0

>>> y imag

5.0 >>> z real -0.0

>>> z imag -5.0

Wecanalsousethebuilt-infunctioncomplex

>>> a =3

>>> b =5

>>> c = complex(a,b)

>>> c (3+5j)

>>> c.real

3.0

>>> c.imag

5.0

Intermsofoperationwecanusethestandardoperatorsshownearliertocomplexnumbersandtheresultsareasfollows

>>> x =3+5j

>>> x (3+5j)

>>> y =5j

>>> y

5j

>>> z =-5j

>>> z (-0-5j)

>>> x + y (3+10j)

>>> x - y (3+0j)

>>> x / y (1-0.6j)

>>> x * y

(-25+15j)

Wecanalsoadd,subtract,divideormultiplyintegersorfloatstoacomplexnumbersas weshow

10.2 (13.2+5j)

>>> x -10 (-7+5j)

>>> x -10.2

(-7.199999999999999+5j)

>>> x *10 (30+50j)

>>> x (3+5j)

>>> x *10.2

(30.599999999999998+51j)

>>> x *10.2

(30.599999999999998+51j)

>>> x /10

(0.3+0.5j)

>>> x /10.2

(0.29411764705882354+0.4901960784313726j)

Inaddingorsubtractinganintegerorfloatwithacomplexwechangeonlytherealpart whichistobeexpected,howeverifwemultiplyordivideweapplythatvalueacrossboth realandimaginaryparts.

NextwelookatbooleanvaluesinPython,thesecanbedefinedusingTrueorFalse

>>> x = True

>>> x True

>>> y = False

>>> y False

Integersorfloatscanbeconvertedintoabooleanusingthebuilt-infunctionbool.This treatsanyvalueas0or0.0asFalseandanyothervaluetobeTrue.

>>> x = bool(1)

>>> x True

>>> y = bool(0.0)

>>> y False

>>> z = bool(-10)

>>> z True

Surprisinglywecanusetheoperatorsinthischapteronbooleanvariables.Thekeyto noteisthatavalueofTrueisevaluatedas1andFalseas0,soyoucanseeexamplesofthis below.

>>> x = True

>>> y = False

>>> x + y 1

>>> x - y 1

>>> x * y 0

>>> x / y

Traceback(mostrecentcalllast):

File "<stdin>",line 1, in <module>

ZeroDivisionError:divisionbyzero

>>> x = True

>>> y = True

>>> x + y 2 >>> x - y 0 >>> x + y 2

x * y 1

x / y 1.0

>>> x = False >>> y = False >>> x + y 0 >>> x - y 0

>>> x * y 0

>>> x / y

Traceback(mostrecentcalllast):

File "<stdin>",line 1, in <module>

ZeroDivisionError:divisionbyzero

Inmostcasestheresultsareasexpectedconsideringthatwearedealingwith1or0inthe operation.HoweveranytimethatwedividebyzerowegetaZeroDivisonErrorsobecareful withzerodivision.

Wecanalsocreatebyte,bytearraysandmemoryviewobjectswiththefollowingsyntax.

>>> x = b"HelloWorld"

>>> x b'HelloWorld'

>>> y = bytearray(6)

>>> y bytearray(b'\x00\x00\x00\x00\x00\x00')

>>> z = memoryview(bytes(5))

>>> z <memoryat 0x7fdde6fea348>

Wecanconcatenatebytestringstogetherinthewaywehaveshownwithstrings

>>> x = b"HelloWorld"

>>> x b'HelloWorld'

>>> y = b"MynameisRob"

>>> y

b'MynameisRob'

>>> x + y

b'HelloWorldMynameisRob'

WhatwehavecoveredinthischapterissomeofthedatatypesinPythonandhowto operateonthemusingstandardmathematicalmethods.Onethingtotakefromthisisthe mechanismthatPythonusestooperateonobjectsandthatissimplylookforamethodthat cantakeintheargumentsthatyoupassintoit.

Operators

Thepreviouschapterintroduceddatatypesandsomebasicoperatorsbutinthischapterwe buildonthisbyintroducinganumberofkeyoperatorsthatareimportanttounderstand. Asshowninourintroductoryexamplesinthepreviouschapter,wecandefineavariableas follows:

>>> x =2+1

>>> x

3

Here,weareassigningthevariablexwiththeresultof1 + 2soxis3.Now,ifwewanted toseeifthevalueofxwasequalto3wewoulduse == whichreferstoequality.

>>> x =2+1

>>> x ==3

True

Wehaveshownhowtotestforequalitybutwhataboutinequality.WellPythonhasthat sortedaswell,insteadofusing == weuse!= whichisnotequals.Usingtheexamplefrom beforewegetthefollowing:

>>> x =2+1

>>> x !=3

False

Whatwehavehereistheresultofanequalitystatementlikethisbeingoftypeboolean (TrueorFalse).

Wecanalsotesttoseeifsomethingisgreaterorlessthananotherelement.

>>> x =2+1

>>> x >4

False

>>> x <4

True

>>> x >=4

False

ThePythonBook,FirstEdition.RobMastrodomenico. ©2022JohnWiley&SonsLtd.Published2022byJohnWiley&SonsLtd.

>>> x >=3

True

>>> x <=3

True

Herewehaveintroducedthefollowingtestswhichtakesthevalueontheleftagainstthe valueontherightandtestsfor

● > forgreaterthan

● < lessthan

● >= greaterthanorequalto

● <= lessthanorequalto

Youcanalsotestforequalityusingthestatementis.Nowitisnotstrictlythesameas using == whichwedemonstrateearlier.EssentiallythedifferenceisthatitreturnsTrueif thevariablesinquestionpointstothesameobjectwhilst == returnsTrueifthevaluesare equal.Itisaverysubtledifferencesoyouneedtobecarefulwithit.Asimplerexplanationis that == returnsTrueifthevariablesbeingcomparedareequal,whereasischeckswhether theyarethesame.Thebelowexamplesshowsthedangersinusingis

>>> a =1

>>> a is 1

a ==1

Inthefirstinstanceaisassignedtobe1andwesayisa1anditissowegetTruereturned. Inthesecondinstanceweassignaandbtobeemptylist(wewillcoverwhatalistislater) andwecanseewereturnFalsewiththeisstatementandTruewiththeequals.Thereason behindthisisthattheyarenotthesamelistsso

>>> a is b

False

However,theyarebothlistssousingthecomparisonstatement == wereturnTrueas theyarebothemptylists.Ifweassignedaasalistandb = awewouldgetthefollowing:

Thereasonbeingisthatbisthesameasasotheyarethesamething.Aswith == and != wehaveisnotagainthe!= isatestofequalitybetweentwovariableswhereasthePython statementisnot,isatestofidentity.Agoodexampleofthisiswhenyoucompareavariable tothePythonNullvaluedenotedasNone.Here,thepreferredwaytowriteitis

>>> a =21

>>> a isnot None

Youcanoverridethevariablebyassigningsomethingtoitlikewedidbefore

>>> x =1 >>> x 1 >>> x =10 >>> x 10

Allprettysimplestuff.Nowifwehavethreevariablesthatwewanttoassignwecando itasfollows

>>> x =1

>>> y =2 >>> z =3 >>> x 1 >>> y 2 >>> z 3

Thisisfinetodohoweverittakesupalotofspacesoinsteadyoucanwriteyourassignmentasfollows

>>> x,y,z =1, 2, 3 >>> x 1

Thisjustmakesiteasiertoassignvariablesandmakesyourcodeshorterandhopefully morereadable.ObviouslythenamingconventionI’veusedforthevariablesisn’tthebest anditmakesforbettercodetogiveyourvariablesmeaningfulnamesasitwillhelpthose whohavetogobackandreadyourcode.

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.
The python book 1st edition rob mastrodomenico all chapter instant download by Education Libraries - Issuu