Where can buy The python book 1st edition rob mastrodomenico ebook with cheap price

Page 1


The Python Book 1st Edition Rob

Visit to download the full and correct content document: https://ebookmass.com/product/the-python-book-1st-edition-rob-mastrodomenico/

More products digital (pdf, epub, mobi) instant download maybe you interests ...

The Python Book 5th Edition Dan Peel

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

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

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

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/

Pearson Edexcel International GCSE (9-1) Business

Student Book 1st Edition

Rob Jones

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

The Python Quiz Book Michael Driscoll

https://ebookmass.com/product/the-python-quiz-book-michaeldriscoll/

The Hill Iain Rob Wright

https://ebookmass.com/product/the-hill-iain-rob-wright/

A Moral Defense of Prostitution 1st Edition Rob

Lovering

https://ebookmass.com/product/a-moral-defense-ofprostitution-1st-edition-rob-lovering/

The Bad Movie Bible Rob Hill

https://ebookmass.com/product/the-bad-movie-bible-rob-hill/

The Red Vienna Sourcebook Rob Mcfarland

https://ebookmass.com/product/the-red-vienna-sourcebook-robmcfarland/

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.

Wehavelookedatassigningvariableshoweverwhatifwewanttodosomethingtothe variablelikesayaddsomethingtothevalue.Letsassumewehaveavariableprofitandwe wanttoadd100.0toit,thenwecoulddoitasfollows

>>> profit =1000.0

>>> profit

1000.0

>>> profit = profit +100

>>> profit

1100.0

Whatwearedoinghereisassigningprofittheinitialvaluethenassigningititsvalueplus 100.ThereisnothingwrongwithwhatwedidherehoweverthemorePythonicwaywould betodothis

>>> profit =1000.0

1000.0 >>> profit +=100.0

1100.0

Similarlyiswewantedtomultiplythevalueby20%wecoulddosoasfollows

>>> profit =1000.0 >>> profit

1000.0

>>> profit *=1.2 >>> profit

1200.0

Asyouwouldthinkwecandothesamefordivisionandsubtraction

1000.0

998.8

profit /=2

499.4

TherearesomeothernontypicaloperatorsthatwecanuseinPython,thefirstonebeing moduluswhichreturnstheremainderofintegerdivision.

>>> x =2

>>> y =10

>>> x/y

0.2

>>> x % y 2

Wecanalsoperformexponentiationasfollows

>>> x =2

>>> y =10

>>> y ** x

100

Pythonalsogivesustheoperatorforfloordivisionwhichwashowdivisionwasusedin Python2howeveritisnowperformedexplicitlyusingtheflooroperator

>>> x =2

>>> y =10

>>> x/y

0.2

>>> x // y

0

Followingonfromwhatweshowedearliertheseoperationscanbeperformedusing theequalsoperatorapproachtoassignbacktothevariable.Sowecanperformmodulus, exponentiationandflooroperationsasfollows.

>>> x =2

>>> y =10

>>> x %= y

>>> x 2

>>> x =2

>>> y =10

>>> y **= x

>>> y

100

>>> x =2

>>> y =10

>>> x //= y

>>> x

0

Wecanalsochaintogetherthesetypesofoperatorsasfollows

>>> x =2

>>> y =10

>>> x < y

True

>>> z =3

>>> a =3

>>> b =3

>>> a == b

True

>>> x < y and a == b

True

>>> x > y

False

>>> x > y and a == b

False

>>> a != b

False

>>> x > y and a != b

False

Sowecancombineourlogicstatementstogethertoformmorecomplexstatements.This willbecomeusefullaterinthebookwhenweapplythesewithotherPythonfunctionality. ThischapterhasshownhowweperformvariousoperationsonPythondatatypesand thiswillformthebasisforlotsofthelogicthatweapplythroughoutthisbook.

Dates

InthepreviouschapterswecoveredsomeofthemaindatatypesinPythonbutonething thatisquiteimportantisdates.Foranyonewhohasworkedwithdatestheycanbetricky things,therearedifferentwaystoformatthemandtheycanbehardtomanipulate,however Pythonhasyoucovered.Ifwewanttocreateadatetimeobjectwedosoasfollows(weearlier showedhowtoimportthedatetimepackage):

>>> from datetime import datetime as dt

>>> d = dt(2017, 5, 17, 12, 10, 11)

>>> d

datetime datetime(2017, 5, 17, 12, 10, 11)

>>> str(d)

"2017-05-1712:10:11"

Whatwehavedonehereiscreateadatetimebypassingintodttheyear,month,day,hour, minute,secondtogiveusadatetimeobject.Ifwewanttoseeitinamorefriendlywaywe cantypestrarounditandwegetthestringrepresentation.Givenwecandefineadatewe canoperateondatesasfollows:

>>> d1 = dt(2017, 5, 17, 12, 10, 11)

>>> d1

datetime.datetime(2017, 5, 17, 12, 10, 11)

>>> d2 = dt(2016, 4, 7, 1, 1, 1)

>>> d2

datetime.datetime(2016, 4, 7, 1, 1, 1)

>>> d1 - d2

datetime.timedelta(405, 40150)

>>> str(d1 - d2) "405days,11:09:10"

Here,wehavecreatedtwodatesandthensubtractedonefromtheother.Whatweget backisatimedeltaobjectandconvertingittoastringwecanseethatitrepresentsthedays andtimefromthedatesubtraction.Tounderstandtimedeltawecanimportitjustaswedid withdatetime.

>>> from datetime import timedelta as td

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

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.