Python Programming

python presentation and need guidance to help me learn.

Python Programming Hans-Petter Halvorsen https://www.halvorsen.blog Python Programming Python Programming Hans-Petter Halvorsen 2019 Python Programming c Hans-Petter Halvorsen August 12, 2020 ISBN:978-82-691106-4-7 1 Preface Python is a popular programming language, and it is one of the most used programming languages today. Python works on all the main platforms and operating systems used today, such Windows, macOS, and Linux. Python is a multi-purpose programming language, which can be use for simulation, creating web pages, communicate with database systems, etc. My Blog/Web Site [1]: https://www.halvorsen.blog Here you find lots of technical resources about Technology, Programming, Software Engineering, Automation and Control, Industrial IT, etc. Here you find my Web page with Python resources: https://www.halvorsen.blog/documents/programming/python/ These resources are a supplement to this textbook. Here you can download the software, download code examples, etc. This Textbook is written in LATEXusing Overleaf. LATEXis a document preparation system used for the communication and publication of scientific documents. 2 For more information about LATEX: https://www.latex-project.org Overleaf is a web-bases LATEXsystem, meaning you can write your LATEXdocuments in your web browser, you co-work and share documents with others. For more information about Overleaf: https://www.overleaf.com Python Books You find other Python textbooks within different domains on my Python Web page: https://www.halvorsen.blog/documents/programming/python/ Python Books: • Python Programming – This is a textbook in Python Programming with lots of Practical Examples and Exercises. You will learn the necessary foundation for basic programming with focus on Python. • Python for Science and Engineering – This is a textbook in Python Programming with lots of Examples, Exercises, and Practical Applications within Mathematics, Simulations, etc. The focus is on numerical calculations in mathematics and engineering. Necessary theory is presented in addition to many practical examples. • Python for Control Engineering – This is a textbook in Python Programming with lots of Examples, Exercises, and Practical Applications within Mathematics, Simulations, Control Systems, DAQ, Database Systems, etc. The focus is on the use of Python within measurements, data collection (DAQ), control technology, both analysis of control systems (stability analysis, frequency response, …) and implementation of control systems (PID, etc.). Required theory is presented in addition to many practical examples and exercises in Python. • Python for Software Development – This is a textbook in Python Programming with lots of Examples, Exercises, and Practical Applications within Software Systems, Software Development, Software Engineering, Database Systems, Web Application Desktop Applications, GUI Applications, etc. The focus is on the use of Python for creating modern Software Systems. Required theory is presented in addition to many practical examples and exercises in Python. 3 Programming The way we create software today has changed dramatically the last 30 years, from the childhood of personal computers in the early 80s to today’s powerful devices such as Smartphones, Tablets and PCs. The Internet has also changed the way we use devices and software. We still have traditional desktop applications, but Web Sites, Web Applications and socalled Apps for Smartphones, etc. are dominating the software market today. We need to find and learn Programming Languages that are suitable for the New Age of Programming. We have today several thousand different Programming Languages today. I guess you will need to learn more than one Programming Language to survive in today’s software market. You find lots of Programming Resources here: https://www.halvorsen.blog/documents/programming/ Software Engineering Software Engineering is the discipline for creating software applications. A systematic approach to the design, development, testing, and maintenance of software. The main parts or phases in the Software Engineering process are: • Planning • Requirements Analysis • Design • Implementation • Testing • Deployment and Maintenance You find lots of Software Engineering Resources here: https://www.halvorsen.blog/documents/programming/softwareengineering/
Requirements:

PythonProgrammingHans-PetterHalvorsen2019
PythonProgrammingc
Hans-PetterHalvorsenAugust12,2020ISBN:978-82-691106-4-71
PrefacePythonisapopularprogramminglanguage,anditisoneofthemostusedpro-gramminglanguagestoday.Pythonworksonallthemainplatformsandoperatingsystemsusedtoday,suchWindows,macOS,andLinux.Pythonisamulti-purposeprogramminglanguage,whichcanbeuseforsimu-lation,creatingwebpages,communicatewithdatabasesystems,etc.MyBlog/WebSite[1]:https://www.halvorsen.blogHereyou ndlotsoftechnicalresourcesaboutTechnology,Programming,Soft-wareEngineering,AutomationandControl,IndustrialIT,etc.Hereyou ndmyWebpagewithPythonresources:https://www.halvorsen.blog/documents/programming/python/Theseresourcesareasupplementtothistextbook.Hereyoucandownloadthesoftware,downloadcodeexamples,etc.ThisTextbookiswritteninLATEXusingOverleaf.LATEXisadocumentpreparationsystemusedforthecommunicationandpubli-cationofscienti cdocuments.2
FormoreinformationaboutLATEX:https://www.latex-project.orgOverleafisaweb-basesLATEXsystem,meaningyoucanwriteyourLATEXdocumentsinyourwebbrowser,youco-workandsharedocumentswithothers.FormoreinformationaboutOverleaf:https://www.overleaf.comPythonBooksYou ndotherPythontextbookswithindi erentdomainsonmyPythonWebpage:https://www.halvorsen.blog/documents/programming/python/PythonBooks:PythonProgramming-ThisisatextbookinPythonProgrammingwithlotsofPracticalExamplesandExercises.YouwilllearnthenecessaryfoundationforbasicprogrammingwithfocusonPython.PythonforScienceandEngineering-ThisisatextbookinPythonProgrammingwithlotsofExamples,Exercises,andPracticalApplicationswithinMathematics,Simulations,etc.Thefocusisonnumericalcalcu-lationsinmathematicsandengineering.Necessarytheoryispresentedinadditiontomanypracticalexamples.PythonforControlEngineering-ThisisatextbookinPythonPro-grammingwithlotsofExamples,Exercises,andPracticalApplicationswithinMathematics,Simulations,ControlSystems,DAQ,DatabaseSys-tems,etc.ThefocusisontheuseofPythonwithinmeasurements,datacollection(DAQ),controltechnology,bothanalysisofcontrolsystems(stabilityanalysis,frequencyresponse,…)andimplementationofcontrolsystems(PID,etc.).RequiredtheoryispresentedinadditiontomanypracticalexamplesandexercisesinPython.PythonforSoftwareDevelopment-ThisisatextbookinPythonPro-grammingwithlotsofExamples,Exercises,andPracticalApplicationswithinSoftwareSystems,SoftwareDevelopment,SoftwareEngineering,DatabaseSystems,WebApplicationDesktopApplications,GUIApplica-tions,etc.ThefocusisontheuseofPythonforcreatingmodernSoftwareSystems.Requiredtheoryispresentedinadditiontomanypracticalex-amplesandexercisesinPython.3
ProgrammingThewaywecreatesoftwaretodayhaschangeddramaticallythelast30years,fromthechildhoodofpersonalcomputersintheearly80stotoday’spowerfuldevicessuchasSmartphones,TabletsandPCs.TheInternethasalsochangedthewayweusedevicesandsoftware.Westillhavetraditionaldesktopapplications,butWebSites,WebApplicationsandso-calledAppsforSmartphones,etc.aredominatingthesoftwaremarkettoday.Weneedto ndandlearnProgrammingLanguagesthataresuitablefortheNewAgeofProgramming.Wehavetodayseveralthousanddi erentProgrammingLanguagestoday.IguessyouwillneedtolearnmorethanoneProgrammingLanguagetosurviveintoday’ssoftwaremarket.You ndlotsofProgrammingResourceshere:https://www.halvorsen.blog/documents/programming/SoftwareEngineeringSoftwareEngineeringisthedisciplineforcreatingsoftwareapplications.Asystematicapproachtothedesign,development,testing,andmaintenanceofsoftware.ThemainpartsorphasesintheSoftwareEngineeringprocessare:PlanningRequirementsAnalysisDesignImplementationTestingDeploymentandMaintenanceYou ndlotsofSoftwareEngineeringResourceshere:https://www.halvorsen.blog/documents/programming/softwareengineering=4
5
ContentsIGettingStartedwithPython101Introduction111.1TheNewAgeofProgramming……………….111.2MATLAB………………………….152WhatisPython?172.1IntroductiontoPython…………………..172.1.1Interpretedvs.Compiled………………182.2PythonPackages………………………192.2.1PythonPackagesforScienceandNumericalComputations202.3Anaconda………………………….202.4PythonEditors……………………….212.4.1PythonIDLE…………………….212.4.2VisualStudioCode………………….222.4.3Spyder………………………..222.4.4VisualStudio…………………….222.4.5PyCharm………………………222.4.6WingPythonIDE………………….232.4.7JupyterNotebook………………….232.5Resources………………………….232.6InstallingPython………………………232.6.1PythonWindows10StoreApp……………242.6.2InstallingAnaconda…………………242.6.3InstallingVisualStudioCode…………….243StartusingPython263.1PythonIDE…………………………263.2My rstPythonprogram………………….263.3PythonShell………………………..273.4RunningPythonfromtheConsole……………..273.4.1OpeningtheConsoleonmacOS……………283.4.2OpeningtheConsoleonWindows………….293.4.3AddPythontoPath…………………293.5ScriptingMode……………………….313.5.1RunPythonScriptsfromthePythonIDLE……..313.5.2RunPythonScriptsfromtheConsole(Terminal)macOS323.5.3RunPythonScriptsfromtheCommandPromptinWin-dows…………………………336
3.5.4RunPythonScriptsfromSpyder…………..334BasicPythonProgramming364.1BasicPythonProgram……………………364.1.1GetHelp………………………364.2Variables………………………….364.2.1Numbers………………………384.2.2Strings………………………..394.2.3StringInput……………………..404.3Built-inFunctions……………………..404.4PythonStandardLibrary………………….414.5UsingPythonLibraries,PackagesandModules……….424.5.1PythonPackages…………………..444.6PlottinginPython……………………..444.6.1Subplots……………………….474.6.2Exercises………………………49IIPythonProgramming505PythonProgramming515.1If…Else………………………….515.2Arrays……………………………525.3ForLoops………………………….545.3.1NestedForLoops…………………..575.4WhileLoops…………………………585.5Exercises………………………….586CreatingFunctionsinPython606.1Introduction…………………………606.2Functionswithmultiplereturnvalues……………626.3Exercises………………………….637CreatingClassesinPython667.1Introduction…………………………667.2Theinit()Function……………………677.3Exercises………………………….708CreatingPythonModules718.1PythonModules………………………718.2Exercises………………………….729FileHandlinginPython749.1Introduction…………………………749.2WriteDatatoaFile…………………….749.3ReadDatafromaFile……………………759.4LoggingDatatoFile…………………….759.5WebResources……………………….769.6Exercises………………………….767
10ErrorHandlinginPython7910.1IntroductiontoErrorHandling……………….7910.1.1SyntaxErrors…………………….7910.1.2Exceptions……………………..7910.2ExceptionsHandling…………………….8011DebugginginPython8212InstallingandusingPythonPackages8312.1WhatisPIP?………………………..83IIIPythonEnvironmentsandDistributions8413IntroductiontoPythonEnvironmentsandDistributions8513.1PackageandEnvironmentManagers…………….8613.1.1PIP…………………………8613.1.2Conda………………………..8613.2PythonVirtualEnvironments………………..8714Anaconda8814.1AnacondaNavigator…………………….8815EnthoughtCanopy90IVPythonEditors9116PythonEditors9217Spyder9418VisualStudioCode9618.1IntroductiontoVisualStudioCode……………..9618.2PythoninVisualStudioCode………………..9719VisualStudio9819.1IntroductiontoVisualStudio………………..9819.2WorkwithPythoninVisualStudio……………..9819.2.1MakeVisualStudioreadyforPythonProgramming…9919.2.2PythonInteractive………………….9919.2.3NewPythonProject…………………10020PyCharm10621WingPythonIDE10822JupyterNotebook11022.1JupyterHub…………………………11122.2MicrosoftAzureNotebooks…………………1118
VPythonforMathematicsApplications11323MathematicsinPython11423.1BasicMathFunctions……………………11423.1.1Exercises………………………11623.2Statistics………………………….11823.2.1IntroductiontoStatistics………………11823.2.2StatisticsfunctionsinPython…………….11923.3TrigonometricFunctions…………………..12123.4Polynomials…………………………125VIResources12824PythonResources12924.1PythonDistributions…………………….12924.2PythonLibraries………………………12924.3PythonEditors……………………….12924.4PythonTutorials………………………13024.5PythoninVisualStudio…………………..130VIISolutionstoExercises1339
PartIGettingStartedwithPython10
Chapter1IntroductionWiththistextbookyouwilllearnbasicPythonprogramming.Thetextbookcontainslotsofexamplesandself-pacedtasksthattheusersshouldgothroughandsolveintheirownpace.Youwill ndadditionalresourcesonmyblog/website[1].https://www.halvorsen.blogMyWebSiteaboutPythonis:https://www.halvorsen.blog/documents/programming/python/SeeFigure1.11.1TheNewAgeofProgrammingThewaywecreatesoftwaretodayhaschangeddramaticallythelast30years,fromthechildhoodofpersonalcomputersintheearly80stotoday’spowerfuldevicessuchasSmartphones,TabletsandPCs.TheInternethasalsochangedthewayweusedevicesandsoftware.Westillhavetraditionaldesktopapplications,butWebSites,WebApplicationsandso-calledAppsforSmartphones,etc.aredominatingthesoftwaremarkettoday.Weneedto ndandlearnProgrammingLanguagesthataresuitablefortheNewAgeofProgramming.Wehavetodayseveralthousanddi erentProgrammingLanguages,sowhyshouldwelearnPython?IguessyouwillneedtolearnmorethanonePro-grammingLanguagetosurviveintoday’ssoftwaremarket.Pythoniseasytolearn,soititagoodstartingpointfornewprogrammers.Pythonisaninterpreted,high-level,general-purposeprogramminglanguage.CreatedbyGuidovanRossumand rstreleasedin1991[2].11
Figure1.1:WebSite-PythonPythonisafairlyoldProgrammingLanguage(1991)comparedtomanyotherProgrammingLanguageslikeC#(2000),Swift(2014),Java(1995),PHP(1995).Pythonhasduringthelast10yearsbecomemoreandmorepopular.Today,PythonhasbecomeoneofthemostpopularProgrammingLanguages.Therearemanydi erentrankingsregardingwhichprogramminglanguagewhichismostpopular.Inmostoftheseranking,Pythonisintop10.OneoftheserankingsistheIEEESpectrum’srankingofthetopprogramminglanguages[3].FromthisrankingweseethatPythonisthemostpopularProgrammingLan-guagein2018.SeeFigure1.2AsweseeinFigure1.2theycategorizethedi erentProgrammingLanguagesintothefollowingcategories:Web12
Figure1.2:TheMostPopularProgrammingLanguagesMobileEnterpriseEmbeddedAccordingtoFigure1.2weseethatPythoncanbeusedtoprogramWebAp-plications,EnterpriseApplicationsandEmbeddedApplications.SofarPythonisnotusedornotoptimizedforcreatingMobileApplications.Wehavetoday2majorMobileplatforms;iOSApplicationsaremainlyprogrammedwiththeSwiftProgramminglanguage,whileAndroidApplicationsaremainlyprogrammedwitheitherJavaorKotlin.Anothersurveyisthe”StackOver
owDeveloperSurvey2018″[4].SeeFigure1.3.Aswecanseefrom[5]andFigure1.4,Pythonbecomesmoreandmorepopularyearbyyear.BasedonFigure1.4,thesource[5]trytopredictthefutureofPython,seeFigure1.5.Basedonthesurveysandstatisticsmentionabove,obviouslyPythonisapro-gramminglanguagethatyoushouldlearn.Letssummarize:PythonisfuntolearnanduseanditisalsonamedaftertheBritishcomedygroupcalledMontyPython.Pythonhasasimpleand
exiblecodestructureandthecodeiseasytoread.13
Figure1.3:TheTopProgrammingLanguages-StackOver
owSurveyPythonishighlyextendableduetoitshighnumberoffreeavailablePythonPackagedandLibrariesPythoncanbeusedonallplatforms(Windows,macOSandLinux).Pythonismulti-purposeandcanbeusedfortoprogramWebApplications,EnterpriseApplicationsandEmbeddedApplications,andwithinDataScienceandEngineeringApplications.ThepopularityofPythonisgrowingfast.PythonisopensourceandfreetouseThegrowingPythoncommunitymakesiteasyto nddocumentation,codeexamplesandgethelpwhenneededIngeneral,Pythonisamultipurposeprogramminglanguagethatcanbeusedinmanysituations.Butthereisnotoneprogramminglanguagewhichisbestinallkindofsituations,soitisimportantthatyouknowaboutandhaveskillsindi erentlanguages.Mylistofrecommendations(oneofmany):VisualStudioandCLabVIEW-agraphicalprogramminglanguagewellsuitedforhardwareintegration,takingmeasurementsanddataloggingMATLAB-NumericalcalculationsandScienti ccomputingPython-Numericalcalculations,andScienti ccomputing,etc.WebProgramming,suchasHTML,CSS,JavaScriptandaServer-sideframework/programminglanguagelikePHP,ASP.NET(CorVB.NET),Django(Pythonbased)14
Figure1.4:TheIncredibleGrowthofPythonDatabases(suchasSQLServerandMySQL)andusingtheStructuredQueryLanguage(SQL)ortheupcomingNoSQLdatabasesAppDevelopmentforthe2mainplatformsiOS(XCodeusingtheSwiftProgrammingLanguage)andAndroid(AndroidStudiousingtheJavaProgrammingLanguageorKotlinProgramminglanguage)Ifyouhaveskillsinmostofthetools,programminglanguagesandframeworksmentionabove,youarewellsuitedforworkingasafull-timeprogrammerorsoftwareengineer.1.2MATLABIfyouarelookingforMATLAB,pleaseseethefollowing:https://www.halvorsen.blog/documents/programming/matlab/15
Figure1.5:TheFutureofPython16
Chapter2WhatisPython?2.1IntroductiontoPythonPythonisanopensourceandcross-platformprogramminglanguage,thathasbecomeincreasinglypopularoverthelasttenyears.Itwas rstreleasedin1991.Latestversionis3.7.0.CPythonisthereferenceimplementationofthePythonprogramminglanguage.WritteninC,CPythonisthedefaultandmostwidely-usedimplementationofthelanguage.Pythonisamulti-purposeprogramminglanguages(duetoitsmanyextensions),examplesarescienti ccomputingandcalculations,simulations,webdevelop-ment(using,e.g.,theDjangoWebframework),etc.PythonHomePage[6]:https://www.python.orgTheprogramminglanguageismaintainedandavailablefrom(PythonSoftwareFoundation):https://www.python.orgHereyoucandownloadthebasicPythonfeaturesinonepackage,whichincludesthePythonprogramminglanguagein-terpreter,andabasiccodeeditor,oranintegrateddevelopmentenvironment,calledIDLE.SeeFigure2.1ButthisisjustthePythoncore,i.e.theinterpreteraverybasiceditor,andtheminimumneededtocreatebasicPythonprograms.Typicallyyouwillneedmorefeaturesforsolvingyourtasks.Thenyoucanin-stallanduseseparatePythonpackagescreatedbythirdparties.Thesepackagesneedtobedownloadedandinstalledseparately(typicallyyouusesomethingcalledPIP),oryouchoosetouse,e.g.,adistributionpackagelikeAnaconda.Pythonisanobject-orientedprogramminglanguage(OOP),butyoucanusePythoninbasicapplicationwithouttheneedtoknowaboutorusetheobject-orientedfeaturesinPython.Pythonisaninterpretedprogramminglanguage,thismeansthatasadeveloper17
Figure2.1:IDLE-BasicPythonEditoryouwritePython(.py) lesinatexteditorandthenputthose lesintothepythoninterpretertobeexecuted.DependingontheEditoryouareusing,thisiseitherdoneautomatically,oryouneedtodoitmanually.HerearesomeimportantPythonsources:[6],[7],[8].2.1.1Interpretedvs.CompiledWhatarethedi erencesbetweenInterpretedprogramminglanguagesandCom-piledprogramminglanguages?Whatkindshouldyouchoose,andwhyshouldyoubother?Programminglanguagesgenerallyfallintooneoftwocategories:CompiledorInterpreted.Withacompiledlanguage,codeyouenterisreducedtoasetofmachine-speci cinstructionsbeforebeingsavedasanexecutable le.Bothapproacheshavetheiradvantagesanddisadvantages.18
Withinterpretedlanguages,thecodeissavedinthesameformatthatyouen-tered.Compiledprogramsgenerallyrunfasterthaninterpretedonesbecauseinterpretedprogramsmustbereducedtomachineinstructionsatrun-time.Itisusuallyeasiertodevelopapplicationsinaninterpretedenvironmentbecauseyoudon’thavetorecompileyourapplicationeachtimeyouwanttotestasmallsection.Pythonisaninterpretedprogramminglanguage,whilee.g.,C/C++aretrans-latedbyrunningthesourcecodethroughacompiler,i.e.,C/C++arecompiledlanguages.Interpretedlanguages,incontrast,mustbeparsed,interpreted,andexecutedeachtimetheprogramisrun.AnotherexampleofaninterpretedprogramminglanguageisPHP,whichismainlyusedtocreatedynamicwebpagesandwebapplications.Compiledlanguagesarealltranslatedbyrunningthesourcecodethroughacompiler.Thisresultsinveryecientcodethatcanbeexecutedanynumberoftimes.Theoverheadforthetranslationisincurredjustonce,whenthesourceiscompiled;thereafter,itneedonlybeloadedandexecuted.Duringthedesignofanapplication,youmightneedtodecidewhethertouseacompiledlanguageoraninterpretedlanguagefortheapplicationsourcecode.Interpretedlanguages,incontrast,mustbeparsed,interpreted,andexecutedeachtimetheprogramisrunThus,aninterpretedlanguageisgenerallymoresuitedfordoing”adhoc”cal-culationsorsimulations,whilecompiledlanguagesarebetterforpermanentapplicationswherespeedisinfocus.2.2PythonPackagesWithPythonyoudon’tgetsomuchoutofthebox.Insteadofhavingallofitsfunctionalitybuiltintoitscore,youneedtoinstalldi erentpackagesfordi erenttopics.Thisapproachhasadvantagesanddisadvantages.Andisadvantageisthatyouneedtoinstallthesepackagesseparatelyandthenlaterimportthesemodulesinyourcode.Thisisalsotypicalapproachforopensourcesoftware,becauseeverybodycancreatetheirownPythonpackagesanddistributethem.Inthatwayyoualso ndPythonpackagesforalmosteverything,fromScienti cComputingtoWebDevelopment.19
Thesepackagesneedtobedownloadedandinstalledseparately,oryouchoosetouse,e.g.,adistributionpackagelikeAnaconda,whereyoutypicallygetthepackagesyouneedforscienti ccomputing.WithAnacondayoutypicallygetthesamefeaturesaswithMATLAB.LotsofPythonpackagesexists,dependingonwhatyouaregoingtosolve.WehavePythonpackagesforDesktopGUIDevelopment,DatabaseDevelop-ment,WebDevelopment,SoftwareDevelopment,etc.SeeanoverviewofApplicationsforPython:https://www.python.org/about/apps/SeealsothePythonPackageIndex(PyPI)website:https://pypi.orgHereyoucansearchfor,downloadandinstallmanyhundredsPythonPackageswithindi erenttopicsandapplications.YoucanalsomakeyourownPythonPackagesanddistributethemhere.2.2.1PythonPackagesforScienceandNumericalCom-putationsSomeimportantPythonPackagesforScienceandNumericalComputationsare:NumPy-NumPyisthefundamentalpackageforscienti ccomputingwithPython[9]SciPy-SciPyisafreeandopen-sourcePythonlibraryusedforscienti ccomputingandtechnicalcomputing.SciPycontainsmodulesforoptimiza-tion,linearalgebra,integration,interpolation,specialfunctions,FFT,sig-nalandimageprocessing,ODEsolversandothertaskscommoninscienceandengineering.[9]Matplotlib-MatplotlibisaPython2Dplottinglibrary.[10]Pandas-PandasPythonDataAnalysisLibrary[11]Thesepackagesneedtobedownloadedandinstalledseparately,oryouchoosetouse,e.g.,adistributionpackagelikeAnaconda,whereyoutypicallygetthepackagesyouneedforscienti ccomputing.WithAnacondayoutypicallygetthesamefeaturesaswithMATLAB.2.3AnacondaAnacondaisadistributionpackage,whereyougetPythoncompiler,PythonpackagesandtheSpydereditor,allinonepackage.AnacondaincludesPython,theJupyterNotebook,andothercommonlyusedpackagesforscienti ccomputinganddatascience.20
Theyo erafreeversion(AnacondaDistribution)andapaidversion(Enter-prise)AnacondaisavailableforWindows,macOS,andLinuxWeb:https://www.anaconda.comWikipedia:https://en.wikipedia.org/wiki/Anaconda(Pythondistribution)SpyderandthePythonpackages(NumPy,SciPy,Matplotlib,…)mentionabove+++areincludedintheAnacondaDistribution.2.4PythonEditorsAnEditorisaprogramwhereyoucreateyourcode(andwhereyoucanrunandtestit).MostEditorshavealsofeaturesforDebugging.ForsimplePythonprogramsyoucanusetheIDLEEditor,butformoreadvancedprogramsabet-tereditorisrecommended.ExamplesofPythonEditors:PythonIDLEVisualStudioCodeSpyderVisualStudioPyCharmWingPythonIDEJupyterNotebookTheseeditorsareshortlydescribedbelowandinmoredetaillaterinthistext-book.Whicheditoryoushouldusedependsonyourbackground,whatkindofcodeeditorsyouhaveusedpreviously,yourprogrammingskills,whatyouraregoingtodevelopinPython,etc.2.4.1PythonIDLETheprogramminglanguageismaintainedandavailablefrom(PythonSoftwareFoundation):https://www.python.orgHereyoucandownloadthebasicPythonfeaturesinonepackage,whichincludesthePythonprogramminglanguagein-terpreter,andabasiccodeeditor,oranintegrateddevelopmentenvironment,calledIDLE.SeeFigure2.1Web:https://www.python.org21
2.4.2VisualStudioCodeVisualStudioCodeisasourcecodeeditordevelopedbyMicrosoftforWindows,LinuxandmacOS.Web:https://code.visualstudio.comResources:GettingStartedwithPythoninVisualStudioCode2.4.3SpyderSpyderisanopensourcecross-platformintegrateddevelopmentenvironment(IDE)forscienti cprogramminginthePythonlanguage.Web:https://www.spyder-ide.orgWikipedia:https://en.wikipedia.org/wiki/Spyder(software)SpyderisincludedintheAnacondaDistribution.2.4.4VisualStudioMicrosoftVisualStudioisanintegrateddevelopmentenvironment(IDE)fromMicrosoft.Itisusedtodevelopcomputerprograms,aswellaswebsites,webapps,webservicesandmobileapps.Thedeafult(main)programminglanguageinVisualstudioisC,butmanyotherprogramminglanguagesaresupported.VisualstudioisavailableforWindowsandmacOS.VisualStudio(from2017),hasintegratedsupportforPython,itiscalled”PythonSupportinVisualStudio”.Web:https://visualstudio.microsoft.comWikipedia:https://en.wikipedia.org/wiki/MicrosoftVisualStudio2.4.5PyCharmPyCharmiscross-platform,withWindows,macOSandLinuxversions.TheCommunityEditionisfreetouse,whiletheProfessionalEdition(paidversion)hassomeextrafeatures.22
Web:https://www.jetbrains.com/pycharm/2.4.6WingPythonIDETheWingPythonIDEfamilyofintegrateddevelopmentenvironments(IDEs)fromWingwarewerecreatedspeci callyforthePythonprogramminglanguage.3di erentversionofWingexists[12]:Wing101{averysimpli edfreeversion,forteachingbeginningpro-grammersWingPersonal{freeversionthatomitssomefeatures,forstudentsandhobbyistsWingPro{afull-featuredcommercial(paid)version,forprofessionalprogrammers2.4.7JupyterNotebookTheJupyterNotebookisanopen-sourcewebapplicationthatallowsyoutocre-ateandsharedocumentsthatcontainlivecode,equations,visualizationsandtext.Web:http://jupyter.orgWikipedia:https://en.wikipedia.org/wiki/ProjectJupyter2.5ResourcesHerearesomeusefulPythonresources:TheocialPythonTutorial-https://docs.python.org/3.7/tutorial/index.htmlTheocialPythonDocumentation-https://docs.python.org/3.7/index.htmlPythonTutorial(w3schools.com)[13]-https://www.w3schools.com/python/2.6InstallingPythonThePythonprogramminglanguageismaintainedandavailablefrom(PythonSoftwareFoundation):23
https://www.python.orgHereyoucandownloadthebasicPythonfeaturesinonepackage,whichincludesthePythonprogramminglanguageinterpreter,andabasiccodeeditor,oranintegrateddevelopmentenvironment,calledIDLE.SeeFigure2.1ForbasicPythonprogrammingthisisgoodenough.FormoreadvancedPythonProgrammingyoutypicallyneedabetterCodeEd-itorandadditionalPackages.ForthebasicPythonexamplesinthebeginning,thebasicPythonsoftwarefrom:https://www.python.orgisgoodenough.IsuggestyoustartwiththebasicPythonsoftwareinordertolearnthebasics,thenyoucanupgradetoabetterEditor,installadditionPythonpackages(eithermanuallyororinstallAnacondawhere”everything”isincluded).2.6.1PythonWindows10StoreAppPython3.7isalsoavailableintheMicrosoftStoreforWindows10.TheMicrosoftStoreversionofPython3.7isasimpli edinstallerforrunningscriptsandpackages.MicrosoftStoreversionofPython3.7isverybasicbutit’sgoodenoughtorunthesimplescripts.Python3.7MicrosoftStoreeditionwillreceiveallupdatesautomaticallywhentheyarereleasedandnomanualactionisrequiredfromyourend.InordertoinstalltheMicrosoftStoreversionofPythonjustopenMicrosoftStoreinWindows10andsearchforPython.2.6.2InstallingAnacondaTheSpyderCodeEditorandthePythonpackages(suchasNumPy,SciPy,mat-plotlib,etc)areincludedintheAnacondaDistribution.Downloadandinstallfrom:https://www.anaconda.com2.6.3InstallingVisualStudioCodeVisualStudioCodecodeisasimpleandeasytouseeditorthatcanbeusedformanydi erentprogramminglanguages.24
Downloadandinstallfrom:https://code.visualstudio.comGettingStartedwithPythoninVisualStudioCode:https://code.visualstudio.com/docs/python/python-tutorial25
Chapter3StartusingPythonInthischapterwewillstarttousePythoninsomesimpleexamples.3.1PythonIDEThebasiccodeeditor,oranintegrateddevelopmentenvironment,calledIDLE.SeeFigure3.1.OtherPythonEditorswillbediscussedmoreindetaillater.FornowyoucanusethebasicPythonIDE(IDLE)orSpyderifyouhaveinstalledtheAnacondadistributionpackage.Figure3.1:PythonShell/PythonIDLEEditor3.2My rstPythonprogramWewillstartusingPythonandcreatesomecodeexamples.26
Example3.2.1.PlottinginPythonLetsopenyourPythonEditorandtypethefollowing:1print(“HelloWorld!”)Listing3.1:HelloWorldPythonExample[EndofExample]Anextremelyusefulcommandishelp(),whichentersahelpfunctionalitytoexploreallthestu pythonletsyoudo,rightfromtheinterpreter.PressqtoclosethehelpwindowandreturntothePythonprompt.YoucanusePythonindi erentways,eitherin”interactive”modeorin”Script-ing”mode.Thepythonprogramthatyouhaveinstalledwillbydefaultactassomethingcalledaninterpreter.Aninterpretertakestextcommandsandrunsthemasyouenterthem-veryhandyfortryingthingsout.YocanrunPythoninteractivelyindi erentwayseitherusingtheConsolewhichispartoftheoperatingsystemorthePythonIDLEandthePythonShellwhichispartofthebasicPythoninstallationfromhttps://www.python.org.3.3PythonShellIninteractiveModeyouusethePythonShellasseeninFigure3.1.Hereyoutypeoneandonecommandatatimeafterthe”>>>”signinthePythonShell.1>>>print(“HelloWorld!”)3.4RunningPythonfromtheConsoleAconsole(or”terminal”,or`commandprompt’)isatextualwaytointeractwithyourOS(OperatingSystem).Thepythonprogramthatyouhaveinstalledwillbydefaultactassomethingcalledaninterpreter.Aninterpretertakestextcommandsandrunsthemasyouenterthem-veryhandyfortryingthingsout.BelowweseehowwecanrunPythonfromtheConsolewhichispartoftheOS.27
3.4.1OpeningtheConsoleonmacOSThestandardconsoleonmacOSisaprogramcalledTerminal.OpenTerminalbynavigatingtoApplications,thenUtilities,thendouble-clicktheTerminalpro-gram.Youcanalsoeasilysearchforitinthesystemsearchtoolinthetopright.ThecommandlineTerminalisatoolforinteractingwithyourcomputer.Awindowwillopenwithacommandlinepromptmessage,somethinglikethis:Lastlogin:TueDec1108:33:51onconsolecomputername:~usernameJusttypepythonatyourconsole,hitEnter,andyoushouldenterPython’sInterpreter.1Lastlogin:TueDec1112:34:16onttys0002HansPetterWorkMacBookAir:~hansha$python3Python3.6.5jAnaconda,Inc.j(default,Apr262018,08:42:37)4[GCC4.2.1CompatibleClang4.0.1(tags/RELEASE401/final)]ondarwin5Type”help”,”copyright”,”credits”or”license”formoreinformation.6>>>Theprompt>>>onthelastlineindicatesthatyouarenowinaninteractivePythoninterpetersession,alsocalledthe\Pythonshell”.Thisisdi erentfromthenormalterminalcommandprompt!Youcannowentersomecodeforpythontorun.Try:>>>print(“HelloWorld”)SealsoFigure3.2.Figure3.2:ConsolemacOSTryotherPythoncommands,e.g.:1>>>a=52>>>b=23>>>x=54>>>y=3a+b5>>>y28
3.4.2OpeningtheConsoleonWindowsWindow’sconsoleiscalledtheCommandPrompt,namedcmd.AneasywaytogettoitisbyusingthekeycombinationWindows+R(Windowsmeaningthewindowslogobutton),whichshouldopenaRundialog.ThentypecmdandhitEnterorclickOk.Youcanalsosearchforitfromthestartmenu.Itshouldlooklike:C:nUsersnmyusername>JusttypepythonintheCommandPrompt,hitEnter,andyoushouldenterPython’sInterpreter.SeeFigure3.3.Figure3.3:CommandPromptWindowsIfyougetanerrormessagelikethis:’python’isnotrecognizedasaninternalorexternalcommand,operableprogramorbatch le.ThenyouneedtoaddPythontoyourpath.Seeinstructionsbelow.Note!Thisisalsoanoptionduringthesetup.Whileinstallingyoucanse-lect”AddPython.exetopath”.Thisoptionisbydefaultsetto”O ”.Togetthatoptionyouneedtoselect”Customize”,notusingthe”Default”installation.3.4.3AddPythontoPathIntheWindowsmenu,searchfor\advancedsystemsettings”andselectViewadvancedsystemsettings.Inthewindowthatappears,clickEnvironmentVariables…nearthebottomright.SeeFigure3.4.29
Figure3.4:WindowsSystemPropertiesInthenextwindow, ndandselecttheuservariablenamedPathandclickEdit…tochangeitsvalue.SeeFigure3.5.Select”New”andaddthepathwhere”python.exe”islocated.SeeFigure3.6.TheDefaultLocationis:C:nUsersnusernAppDatanLocalnProgramsnPythonnPython3732nClickSaveandopentheCommandPromptoncemoreandenter”python”toverifyitworks.SeeFigure3.3.30
Figure3.5:WindowsSystemProperties3.5ScriptingModeIn”Scripting”modeyoucanwriteaPythonProgramwithmultiplePythoncommandsandthensaveitasa le(.py).3.5.1RunPythonScriptsfromthePythonIDLEFromthePythonShellyouselectFile!NewFile,oryoucanopenanexistingPythoprogramorPythonScriptbyselectingFile!Open…LetscreateanewScriptandtypeinthefollowing:1print(“Hello”)2print(“World”)3print(“Howareyou?”)InFigure3.7weseehowthisisdone.AsyouseewecanentermanyPythoncommandsthattogethermakesaPythonprogramorPythonscript.FromthePythonShellyouselectRun!RunModuleorhitF5inordertorunorexecutethePythonScript.SeeFigure3.8.31
Figure3.6:WindowsSystemPropertiesTheIDLEeditorisverybasic,formorecomplicatedtasksyoutypicallymayprefertouseanothereditorlikeSpyder,VisualStudioCode,etc.3.5.2RunPythonScriptsfromtheConsole(Terminal)macOSFromtheConsole(Terminal)onmacOS:1$cd/Users/username/Downloads2$pythonhelloworld.pyNote!Makesureyouareatyoursystemcommandprompt,whichwillhave$or>attheend,notinPythonmode(whichhas>>>instead)!SeealsoFigure3.9.Thenitrespondswith:1Hello2World3Howareyou?32
Figure3.7:PythonScript3.5.3RunPythonScriptsfromtheCommandPromptinWindowsFromCommandPromptinWindow:1>cd/2>cdTemp3>pythonhelloworld.pyNote!Makesureyouareatyoursystemcommandprompt,whichwillhave>attheend,notinPythonmode(whichhas>>>instead)!SeealsoFigure3.10.Thenitrespondswith:1Hello2World3Howareyou?3.5.4RunPythonScriptsfromSpyderIfyouhaveinstalledtheAnacondadistributionpackageyoucanusetheSpydereditor.See3.11.IntheSpydereditorwehavetheScriptEditortotheleftandtheinteractivePythonShellortheConsolewindowtotheright.SeeSee3.11.33
Figure3.8:RunningaPythonScriptFigure3.9:RunningPythonScriptsfromConsolewindowonmacOSFigure3.10:RunningPythonScriptsfromConsolewindowonmacOS34
Figure3.11:RunningaPythonScriptinSpyder35
Chapter4BasicPythonProgramming4.1BasicPythonProgramWewillstartusingPythonandcreatesomecodeexamples.WeusethebasicIDLEeditor(oranotherPythonEditor)Example4.1.1.HelloWorldExampleLetsopenyourPythonEditorandtypethefollowing:1print(“HelloWorld!”)Listing4.1:HelloWorldPythonExample[EndofExample]4.1.1GetHelpAnextremelyusefulcommandishelp(),whichentersahelpfunctionalitytoexploreallthestu pythonletsyoudo,rightfromtheinterpreter.PressqtoclosethehelpwindowandreturntothePythonprompt.4.2VariablesVariablesarede nedwiththeassignmentoperator,\=”.Pythonisdynamicallytyped,meaningthatvariablescanbeassignedwithoutdeclaringtheirtype,andthattheirtypecanchange.Valuescancomefromconstants,fromcomputationinvolvingvaluesofothervariables,orfromtheoutputofafunction.Python36
Example4.2.1.CreatingandusingVariablesinPythonWeusethebasicIDLE(oranotherPythonEditor)andtypethefollowing:1>>>x=32>>>x33Listing4.2:UsingVariablesinPythonHerewede neavariableandsetsthevalueequalto3andthenprinttheresulttothescreen.[EndofExample]YoucanwriteonecommandbytimeintheIDLE.IfyouquitIDLEthevariablesanddataarelost.Therefore,ifyouwanttowriteasomewhatlongerprogram,youarebettero usingatexteditortopreparetheinputfortheinterpreterandrunningitwiththat leasinputinstead.Thisisknownascreatingascript.Pythonscriptsorprogramsaresaveasatext lewiththeextension.pyExample4.2.2.CalculationsinPythonWecanusevariablesinacalculationlikethis:1x=32y=3x3print(y)Listing4.3:UsingandPrintingVariablesinPythonWecanimplementingtheformulay=ax+blikethis:1a=22b=53x=345y=ax+b67print(y)Listing4.4:CalculationsinPythonAsseenintheexamples,youcanusetheprint()commandinordertoshowthevaluesonthescreen.[EndofExample]37
Avariablecanhaveashortname(likexandy)oramoredescriptivename(sum,amount,etc).Youdonneedtode nethevariablesbeforeyouusethem(likeyouneedtotoin,e.g.,C/C++/C).Figure4.1showtheseexamplesusingthebasicIDLEeditor.Figure4.1:BasicPythonHerearesomebasicrulesforPythonvariables:AvariablenamemuststartwithaletterortheunderscorecharacterAvariablenamecannotstartwithanumberAvariablenamecanonlycontainalpha-numericcharacters(A-z,0-9)andunderscoresVariablenamesarecase-sensitive,e.g.,amount,AmountandAMOUNTarethreedi erentvariables.4.2.1NumbersTherearethreenumerictypesinPython:int
oatcomplex38
Variablesofnumerictypesarecreatedwhenyouassignavaluetothem,soinnormalcodingyoudon’tneedtobother.Example4.2.3.NumericTypesinPython1x=1#int2y=2.8#float3z=3+2j#complexListing4.5:NumericTypesinPythonThismeansyoujustassignvaluestoavariablewithoutworryingaboutwhatkindofdatatypeitis.1print(type(x))2print(type(y))3print(type(z))Listing4.6:CheckDataTypesinPythonIfyouusetheSpyderEditor,youcanseethedatatypesthatavariablehasusingtheVariableExplorer(Figure4.2):Figure4.2:VariableEditorinSpyder[EndofExample]4.2.2StringsStringsinPythonaresurroundedbyeithersinglequotationmarks,ordoublequotationmarks.’Hello’isthesameas”Hello”.Stringscanbeoutputtoscreenusingtheprintfunction.Forexample:print(“Hello”).Example4.2.4.PlottinginPythonBelowweseeexamplesofusingstringsinPython:1a=”HelloWorld!”23print(a)45print(a[1])6print(a[2:5])7print(len(a))8print(a.lower())39
9print(a.upper())10print(a.replace(“H”,”J”))11print(a.split(“”))Listing4.7:StringsinPythonAsyouseeintheexample,therearemanybuilt-infunctionsformmanipulatingstringsinPython.TheExampleshowsonlyafewofthem.StringsinPythonarearraysofbytes,andwecanuseindextogetaspeci ccharacterwithinthestringasshownintheexamplecode.[EndofExample]4.2.3StringInputPythonallowsforcommandlineinput.Thatmeansweareabletoasktheuserforinput.Example4.2.5.PlottinginPythonThefollowingexampleasksfortheuser’sname,then,byusingtheinput()method,theprogramprintsthenametothescreen:1print(“Enteryourname:”)2x=input()3print(“Hello,”+x)Listing4.8:StringInput[EndofExample]4.3Built-inFunctionsPythonconsistsoflotsofbuilt-infunctions.Someexamplesaretheprint(9functionthatwealreadyhaveused(perhapswithoutnoticingitisactuallyaBuilt-infunction).Pythonalsoconsistsofdi erentModules,LibrariesorPackages.TheseMod-ules,LibrariesorPackagesconsistsoflotsofprede nedfunctionsfordi erenttopicsorareas,suchasmathematics,plotting,handlingdatabasesystems,etc.SeeSection4.4formoreinformationanddetailsregardingthis.Inanotherchapterwewilllearntocreateourownfunctionsfromscratch.40
4.4PythonStandardLibraryPythonallowsyoutosplityourprogramintomodulesthatcanbereusedinotherPythonprograms.Itcomeswithalargecollectionofstandardmodulesthatyoucanuseasthebasisofyourprograms.ThePythonStandardLibraryconsistsofdi erentmodulesforhandling leI/O,basicmathematics,etc.Youdon’tneedtoinstalltheseseparately,butyouneedtoimportantthemwhenyouwanttousesomeofthesemodulesorsomeofthefunctionswithinthesemodules.Themathmodulehasallthebasicmathfunctionsyouneed,suchas:Trigono-metricfunctions:sin(x),cos(x),etc.Logarithmicfunctions:log(),log10(),etc.Constantslikepi,e,inf,nan,etc.etc.Example4.4.1.UsingthemathmoduleWecreatesomebasicexampleshowtouseaLibrary,aPackageoraModule:Ifweneedonlythesin()functionwecandolikethis:1frommathimportsin23x=3.144y=sin(x)56print(y)Ifweneedafewfunctionswecandolikethis1frommathimportsin,cos23x=3.144y=sin(x)5print(y)67y=cos(x)8print(y)Ifweneedmanyfunctionswecandolikethis:1frommathimport23x=3.144y=sin(x)5print(y)67y=cos(x)8print(y)Wecanalsousethisalternative:1importmath23x=3.144y=math.sin(x)56print(y)41
Wecanalsowriteitlikethis:1importmathasmt23x=3.144y=mt.sin(x)56print(y)[EndofExample]Thereareadvantagesanddisadvantageswiththedi erentapproaches.Inyourprogramyoumayneedtousefunctionsfrommanydi erentmodulesorpack-ages.Ifyouimportthewholemoduleinsteadofjustthefunction(s)youneedyouusemoreofthecomputermemory.Veryoftenwealsoneedtoimportandusemultiplelibrarieswherethedi erentlibrarieshavesomefunctionswiththesamenamebutdi erentuse.OtherusefulmodulesinthePythonStandardLibraryarestatistics(whereyouhavefunctionslikemean(),stdev(),etc.)FormoreinformationaboutthefunctionsinthePythonStandardLibrary,see:https://docs.python.org/3/library/index.html4.5UsingPythonLibraries,PackagesandMod-ulesRatherthanhavingallofitsfunctionalitybuiltintoitscore,Pythonwasde-signedtobehighlyextensible.Thisapproachhasadvantagesanddisadvantages.Andisadvantageisthatyouneedtoinstallthesepackagesseparatelyandthenlaterimportthesemodulesinyourcode.Someimportantpackagesare:NumPy-NumPyisthefundamentalpackageforscienti ccomputingwithPythonSciPy-SciPyisafreeandopen-sourcePythonlibraryusedforscienti ccomputingandtechnicalcomputing.SciPycontainsmodulesforoptimiza-tion,linearalgebra,integration,interpolation,specialfunctions,FFT,sig-nalandimageprocessing,ODEsolversandothertaskscommoninscienceandengineering.Matplotlib-MatplotlibisaPython2Dplottinglibrary42
Lotsofotherpackagesexists,dependingonwhatyouaregoingtosolve.Thesepackagesneedtobedownloadedandinstalledseparately,oryouchoosetouse,e.g.,adistributionpackagelikeAnaconda.Hereyou ndanoverviewoftheNumPylibrary:http://www.numpy.orgHereyou ndanoverviewoftheSciPylibrary:https://www.scipy.orgHereyou ndanoverviewoftheMatplotliblibrary:https://matplotlib.orgYouwilllearnthebasicsfeaturesinalltheselibraries.Wewillusealloftheindi erentexamplesandexercisesthroughoutthistextbook.Example4.5.1.UsinglibrariesInthisexampleweusetheNumPylibrary:1importnumpyasnp23x=345y=np.sin(x)67print(y)InthisexampleweuseboththemathmoduleinthePythonStandardLibraryandtheNumPylibrary:1importmathasmt2importnumpyasnp34x=356y=mt.sin(x)78print(y)91011y=np.sin(x)1213print(y)Note!Asseeninthisexampleweuseafunctioncalledsin()whichexistsbothinthemathmoduleinthePythonStandardLibraryandtheNumPylibrary.Inthiscasetheygivethesameresults.Inthiscasethefollowingcodeisnotrecommended:1frommathimport2fromnumpyimport34x=3543
6y=sin(x)78print(y)91011y=sin(x)1213print(y)Inthiscaseitworks,butassumeyouhave2di erentfunctionswiththesamenamethathavedi erentmeaningin2di erentlibraries.[EndofExample]4.5.1PythonPackagesInadditiontothePythonStandardLibrary,thereisagrowingcollectionofsev-eralthousandcomponents(fromindividualprogramsandmodulestopackagesandentireapplicationdevelopmentframeworks),availablefromthePythonPackageIndex.PythonPackageIndex(PYPI):https://pypi.orgHereyoucandownloadandinstallindividualPythonpackages.AneasyalternativeistheAnacondaDistribution,wheremanyofthemostusedPythonpackagesareincluded.Anaconda:https://www.anaconda.com/distribution/4.6PlottinginPythonTypicallyyouneedtocreatesomeplotsorcharts.InordertomakeplotsorchartsinPythonyouwillneedanexternallibrary.ThemostusedlibraryisMatplotlib.MatplotlibisaPython2DplottinglibraryHereyou ndanoverviewoftheMatplotliblibrary:https://matplotlib.orgIfyouarefamiliarwithMATLABandbasicplottinginMATLAB,usingtheMatplotlibisverysimilar.Themaindi erencefromMATLABisthatyouneedtoimportthelibrary,eitherthewholelibraryoroneormorefunctions.Forsimplicityweimportthewholelibrarylikethis:1importmatplotlib.pyplotasplt44
Plottingfunctionsthatyouwillusealot:plot()title()xlabel()ylabel()axis()grid()subplot()legend()show()LetscreatesomebasicplottingexamplesusingtheMatplotliblibrary:Example4.6.1.PlottinginPythonInthisexamplewehavetoarrayswithdata.Wewanttoplotxvs.y.WecanassumexisatimeseriesandyisthecorrespondingtemperatureidegreesCelsius.1importmatplotlib.pyplotasplt23x=[1,2,3,4,5,6,7,8,9,10]45y=[5,2,4,4,8,7,4,8,10,9]67plt.plot(x,y)8plt.xlabel(‘Time(s)’)9plt.ylabel(‘Temperature(degC)’)10plt.show()Wegetthefollowingplot:Wecanalsowritelikethis:1frommatplotlib.pyplotimport23x=[1,2,3,4,5,6,7,8,9,10]4y=[5,2,4,4,8,7,4,8,10,9]56plot(x,y)7xlabel(‘Time(s)’)8ylabel(‘Temperature(degC)’)9show()Thismakesthecodesimplertoread.oneproblemwiththisapproachappearsassumingweimportandusemultiplelibrariesandthedi erentlibrarieshavesomefunctionswiththesamenamebutdi erentuse.45
Figure4.3:PlottinginPython[EndofExample]Wehaveused4basicplottingfunctionintheMatplotliblibrary:plot()xlabel()ylabel()show()Example4.6.2.PlottingaSineCurve1importnumpyasnp2importmatplotlib.pyplotasplt34x=[0,1,2,3,4,5,6,7]56y=np.sin(x)78plt.plot(x,y)9plt.xlabel(‘x’)10plt.ylabel(‘y’)11plt.show()Thisgivesthefollowingplot(seeFigure4.4):Abettersolutionwillthenbe:46
Figure4.4:PlottingaSinefunctioninPython1importmatplotlib.pyplotasplt2importnumpyasnp34xstart=05xstop=2np.pi6increment=0.178x=np.arange(xstart,xstop,increment)910y=np.sin(x)1112plt.plot(x,y)13plt.xlabel(‘x’)14plt.ylabel(‘y’)15plt.show()Thisgivesthefollowingplot(seeFigure4.5):Ifyouwantgridsyoucanusethegrid()function.[EndofExample]4.6.1SubplotsThesubplotcommandenablesyoutodisplaymultipleplotsinthesamewindow.Typing”subplot(m,n,p)”partitionsthe gurewindowintoanm-by-nmatrixofsmallsubplotsandselectsthesubplotforthecurrentplot.Theplotsarenumberedalongthe rstrowofthe gurewindow,thenthesecondrow,andsoon.SeeFigure4.6.Example4.6.3.CreatingSubplots47
Figure4.5:PlottingaSinefunctioninPython-BetterImplementationWewillcreateandplotsin()andcos()in2di erentsubplots.1importmatplotlib.pyplotasplt2importnumpyasnp34xstart=05xstop=2np.pi6increment=0.178x=np.arange(xstart,xstop,increment)910y=np.sin(x)1112z=np.cos(x)131415plt.subplot(2,1,1)16plt.plot(x,y,’g’)17plt.title(‘sin’)18plt.xlabel(‘x’)19plt.ylabel(‘sin(x)’)20plt.grid()21plt.show()222324plt.subplot(2,1,2)25plt.plot(x,z,’r’)26plt.title(‘cos’)27plt.xlabel(‘x’)28plt.ylabel(‘cos(x)’)29plt.grid()30plt.show()[EndofExample]48
Figure4.6:CreatingSubplotsinPython4.6.2ExercisesBelowyou nddi erentself-pacedExercisesthatyoushouldgothroughandsolveonyourown.TheonlywaytolearnPythonistodolotsofExercises!Exercise4.6.1.Createsin(x)andcos(x)in2di erentplotsCreatesin(x)andcos(x)in2di erentplots.YoushoulduseallthePlottingfunctionslistedbelowinyourcode:plot()title()xlabel()ylabel()axis()grid()legend()show()[EndofExercise]49
PartIIPythonProgramming50
Chapter5PythonProgrammingWehavebeenthroughthebasicsinPython,suchasvariables,usingsomebasicbuilt-infunctions,basicplotting,etc.Youmaycomefaronlyusingthesethins,buttocreaterealapplications,youneedtoknowaboutandusefeatureslike:If…ElseForLoopsWhileLoopsArrays…Ifyouarefamiliarwithoneormoreotherprogramminglanguage,thesefea-turesshouldbefamiliarandknowntoyou.Allprogramminglanguageshasthesefeaturesbuilt-in,butthesyntaxisslightlydi erentfromonelanguagetoanother.5.1If…ElseAn”ifstatement”iswrittenbyusingtheifkeyword.HerearesomeExampleshowyouuseaIfsentencesinPython:Example5.1.1.UsingForLoopsinPython1a=52b=834ifa>b:5print(“aisgreaterthanb”)67ifb>a:8print(“bisgreaterthana”)910ifa==b:11print(“aisequaltob”)Listing5.1:UsingArraysinPython51
Trytochangethevaluesforaandb.UsingIf-Else:1a=52b=834ifa>b:5print(“aisgreaterthanb”)6else:7print(“bisgreaterthanaoraandbareequal”)Listing5.2:UsingArraysinPythonUsingElif:1a=52b=834ifa>b:5print(“aisgreaterthanb”)6elifb>a:7print(“bisgreaterthana”)8elifa==b:9print(“aisequaltob”)Listing5.3:UsingArraysinPythonNote!Pythonuses”elif”not”elseif”likemanyotherprogramminglanguagesdo.[EndofExample]5.2ArraysAnarrayisaspecialvariable,whichcanholdmorethanonevalueatatime.HerearesomeExampleshowyoucancreateanduseArraysinPython:Example5.2.1.UsingForLoopsinPython1data=[1.6,3.4,5.5,9.4]23N=len(data)45print(N)67print(data[2])89data[2]=7.31011print(data[2])121314forxindata:15print(x)52
161718data.append(11.4)192021N=len(data)2223print(N)242526forxindata:27print(x)Listing5.4:UsingArraysinPythonYoude neanarraylikethis:1data=[1.6,3.4,5.5,9.4]Youcanalsousetextlikethis:1carlist=[“Volvo”,”Tesla”,”Ford”]YoucanuseArraysinLoopslikethis:1forxindata:2print(x)Youcanreturnthenumberofelementsinthearraylikethis:1N=len(data)Youcangetaspeci cvalueinsidethearraylikethis:1index=22x=cars[index]Youcanusetheappend()methodtoaddanelementtoanarray:1data.append(11.4)[EndofExample]Youhavemanybuiltinmethodsyoucanuseincombinationwitharrays,likesort(),clear(),copy(),count(),insert(),remove(),etc.Youshouldlooktestallthesemethods.53
5.3ForLoopsAForloopisusedforiteratingoverasequence.IguessallyourprogramswilluseoneormoreForloops.SoifyouhavenotusedForloopsbefore,makesuretolearnitnow.BelowyouseeabasicexamplehowyoucanuseaForloopinPython:1foriinrange(1,10):2print(i)TheForloopisprobablyoneofthemostusefulfeatureinPython(orinanykindofprogramminglanguage).Belowyouwillseedi erentexampleshowyoucanuseaForloopinPython.Example5.3.1.UsingForLoopsinPython1data=[1.6,3.4,5.5,9.4]23forxindata:4print(x)567carlist=[“Volvo”,”Tesla”,”Ford”]89forcarincarlist:10print(car)Listing5.5:UsingForLoopsinPythonTherange()functionishandyyouseinForLoops:1N=1023forxinrange(N):4print(x)Therange()functionreturnsasequenceofnumbers,startingfrom0bydefault,andincrementsby1(bydefault),andendsataspeci ednumber.Youcanalsousetherange()functionlikethis:1start=42stop=12#butnotincluding34forxinrange(start,stop):5print(x)Finally,youcanalsousetherange()functionlikethis:1start=42stop=12#butnotincluding3step=245forxinrange(start,stop,step):6print(x)54
YoushouldtryalltheseexamplesinordertolearnthebasicstructureofaForloop.[EndofExample]Example5.3.2.UsingForLoopsforSummationofDataYoutypicallywanttouseaForloopfor ndthesumofagivendataset.1data=[1,5,6,3,12,3]23sum=045#FindtheSumofallthenumbers6forxindata:7sum=sum+x89print(sum)1011#FindtheMeanorAverageofallthenumbers1213N=len(data)1415mean=sum/N1617print(mean)Thisgivesthefollowingresults:13025.0[EndofExample]Example5.3.3.ImplementingFibonacciNumbersUsingaForLoopinPythonFibonaccinumbersareusedintheanalysisof nancialmarkets,instrategiessuchasFibonacciretracement,andareusedincomputeralgorithmssuchastheFibonaccisearchtechniqueandtheFibonacciheapdatastructure.Theyalsoappearinbiologicalsettings,suchasbranchingintrees,arrangementofleavesonastem,thefruitletsofapineapple,the
oweringofartichoke,anuncurlingfernandthearrangementofapinecone.Inmathematics,Fibonaccinumbersarethenumbersinthefollowingsequence:0,1,1,2,3,5,8,13,21,34,55,89,144,…Byde nition,the rsttwoFibonaccinumbersare0and1,andeachsubsequentnumberisthesumoftheprevioustwo.Somesourcesomittheinitial0,insteadbeginningthesequencewithtwo1s.55
Inmathematicalterms,thesequenceFnofFibonaccinumbersisde nedbytherecurrencerelationfn=fn1+fn2(5.1)withseedvalues:f0=0;f1=1WewillwriteaPythonscriptthatcalculatestheN rstFibonaccinumbers.ThePythonScriptbecomeslikethis:1N=1023fib1=04fib2=156print(fib1)7print(fib2)89forkinrange(N2):10fibnext=fib2+fib111fib1=fib212fib2=fibnext13print(fibnext)Listing5.6:FibonacciNumbersUsingaForLoopinPythonAlternativesolution:1N=1023fib=[0,1]456forkinrange(N2):7fibnext=fib[k+1]+fib[k]8fib.append(fibnext)910print(fib)Listing5.7:FibonacciNumbersUsingaForLoopinPython-Alt2Anotheralternativesolution:1N=1023fib=[]45forkinrange(N):6fib.append(0)78fib[0]=09fib[1]=11056
11forkinrange(N2):12fib[k+2]=fib[k+1]+fib[k]131415print(fib)Listing5.8:FibonacciNumbersUsingaForLoopinPython-Alt3Anotheralternativesolution:1importnumpyasnp234N=1056fib=np.zeros(N)78fib[0]=09fib[1]=11011forkinrange(N2):12fib[k+2]=fib[k+1]+fib[k]131415print(fib)Listing5.9:FibonacciNumbersUsingaForLoopinPython-Alt4[EndofExample]5.3.1NestedForLoopsInPythonandotherprogramminglanguagesyoucanuseoneloopinsidean-otherloop.SyntaxfornestedForloopsinPython:1foriteratingvarinsequence:2foriteratingvarinsequence:3statements(s)4statements(s)Simpleexample:1foriinrange(1,10):2forkinrange(1,10):3print(i,k)Exercise5.3.1.PrimeNumbersThe rst25primenumbers(alltheprimenumberslessthan100)are:2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,9757
Byde nitionaprimenumberhasboth1anditselfasadivisor.Ifithasanyotherdivisor,itcannotbeprime.Anaturalnumber(1,2,3,4,5,6,etc.)iscalledaprimenumber(oraprime)ifitisgreaterthan1andcannotbewrittenasaproductoftwonaturalnumbersthatarebothsmallerthanit.CreateaPythonScriptwhereyou ndallprimenumbersbetween1and200.Tip!Iguessthiscanbedoneinmanydi erentways,butonewayistouse2nestedForLoops.[EndofExercise]5.4WhileLoopsThewhilelooprepeatsagroupofstatementsaninde nitenumberoftimesundercontrolofalogicalcondition.Example5.4.1.UsingWhileLoopsinPython1m=823whilem>2:4print(m)5m=m1Listing5.10:UsingWhileLoopsinPython[EndofExample]5.5ExercisesBelowyou nddi erentself-pacedExercisesthatyoushouldgothroughandsolveonyourown.TheonlywaytolearnPythonistodolotsofExercises!Exercise5.5.1.PlotofDynamicSystemGiventheautonomoussystem:_x=ax(5.2)Where:a=1T58
whereTisthetimeconstant.Thesolutionforthedi erentialequationis:x(t)=eatx0(5.3)SetT=5andtheinitialconditionx(0)=1.CreateaScriptinPython(.py le)whereyouplotthesolutionx(t)inthetimeinterval:0t25AddGrid,andproperTitleandAxisLabelstotheplot.[EndofExercise]59
Chapter6CreatingFunctionsinPython6.1IntroductionAfunctionisablockofcodewhichonlyrunswhenitiscalled.Youcanpassdata,knownasparameters,intoafunction.Afunctioncanreturndataasaresult.Previouslywehavebeenusingmanyofthebuilt-infunctionsinPythonIfyouarefamiliarwithoneormoreotherprogramminglanguage,creatingandusingfunctionsshouldbefamiliarandknowntoyou.Allprogramminglan-guageshasthepossibilitytocreatefunctions,butthesyntaxisslightlydi erentfromonelanguagetoanother.SomeprogramminglanguagesusesthetermMethodinsteadofaFunction.FunctionsandMethodsbehaveinthesamemanner,butyoucouldsaythatMethodsarefunctionsthatbelongstoaClass.WewilllearnmoreaboutClassesinChapter7.Scriptsvs.FunctionsItisimportanttoknowthedi erencebetweenaScriptandaFunction.Scripts:AcollectionofcommandsthatyouwouldexecuteintheEditorUsedforautomatingrepetitivetasksFunctions:Operateoninformation(inputs)fedintothemandreturnoutputsHaveaseparateworkspaceandinternalvariablesthatisonlyvalidinsidethefunction60
Yourownuser-de nedfunctionsworkthesamewayasthebuilt-infunc-tionsyouuseallthetime,suchasplot(),rand(),mean(),std(),etc.Pythonhavelotsofbuilt-infunctions,butveryoftenweneedtocreateourownfunctions(wecouldrefertothesefunctionsasuser-de nedfunctions)InPythonafunctionisde nedusingthedefkeyword:1defFunctionName:23.4.56return…Example6.1.1.CreateaFunctioninaseparateFileBelowyouseeasimplefunctioncreatedinPython:1defadd(x,y):23returnx+yListing6.1:BasicPythonFunctionThefunctionadds2numbers.Thenameofthefunctionisadd,anditreturnstheanswerusingthereturnstatement.Thestatementreturn[expression]exitsafunction,optionallypassingbackanexpressiontothecaller.AreturnstatementwithnoargumentsisthesameasreturnNone.Notethatyouneedtouseacolon”:”attheendoflinewhereyoude nethefunction.Notealsotheindentionused.1defadd(x,y):HereyouseeaPythonscriptwhereweusethefunction:1defadd(x,y):23returnx+y456x=27y=589z=add(x,y)1011print(z)Listing6.2:CreatingandUsingaPythonFunction61
[EndofExample]Example6.1.2.CreateaFunctioninaseparateFileWestartbycreatingaseparatePythonFile(myfunctions.py)forthefunction:1defaverage(x,y):23return(x+y)/2Listing6.3:FunctioncalculatingtheAverageNext,wecreateanewPythonFile(e.g.,testaverage.py)whereweusethefunctionwecreated:1frommyfunctionsimportaverage23a=24b=356c=average(a,b)78print(c)Listing6.4:TestofAveragefunction[EndofExample]6.2FunctionswithmultiplereturnvaluesTypicallywewanttoreturnmorethanonevaluefromafunction.Example6.2.1.CreateaFunctionFunctionwithmultiplereturnvaluesCreatethefollowingexample:1defstat(x):23totalsum=045#FindtheSumofallthenumbers6forxindata:7totalsum=totalsum+x8910#FindtheMeanorAverageofallthenumbers1112N=len(data)1314mean=totalsum/N151617returntotalsum,mean18192062
21data=[1,5,6,3,12,3]222324totalsum,mean=stat(data)2526print(totalsum,mean)Listing6.5:Functionwithmultiplereturnvalues[EndofExample]6.3ExercisesBelowyou nddi erentself-pacedExercisesthatyoushouldgothroughandsolveonyourown.TheonlywaytolearnPythonistodolotsofExercises!Exercise6.3.1.CreatePythonFunctionCreateafunctioncalcaveragethat ndstheaverageoftwonumbers.[EndofExercise]Exercise6.3.2.CreatePythonfunctionsforconvertingbetweenradiansanddegreesSincemostofthetrigonometricfunctionsrequirethattheangleisexpressedinradians,wewillcreateourownfunctionsinordertoconvertbetweenradiansanddegrees.Itisquiteeasytoconvertfromradianstodegreesorfromdegreestoradians.Wehavethat:2[radians]=360[degrees](6.1)Thisgives:d[degrees]=r[radians](180)(6.2)andr[radians]=d[degrees](180)(6.3)Createtwofunctionsthatconvertfromradianstodegrees(r2d(x))andfromdegreestoradians(d2r(x))respectively.ThesefunctionsshouldbesavedinonePython le.py.Testthefunctionstomakesurethattheyworkasexpected.63
[EndofExercise]Exercise6.3.3.CreateaFunctionthatImplementingFibonacciNumbersFibonaccinumbersareusedintheanalysisof nancialmarkets,instrategiessuchasFibonacciretracement,andareusedincomputeralgorithmssuchastheFibonaccisearchtechniqueandtheFibonacciheapdatastructure.Theyalsoappearinbiologicalsettings,suchasbranchingintrees,arrangementofleavesonastem,thefruitletsofapineapple,the
oweringofartichoke,anuncurlingfernandthearrangementofapinecone.Inmathematics,Fibonaccinumbersarethenumbersinthefollowingsequence:0,1,1,2,3,5,8,13,21,34,55,89,144,…Byde nition,the rsttwoFibonaccinumbersare0and1,andeachsubsequentnumberisthesumoftheprevioustwo.Somesourcesomittheinitial0,insteadbeginningthesequencewithtwo1s.Inmathematicalterms,thesequenceFnofFibonaccinumbersisde nedbytherecurrencerelationfn=fn1+fn2(6.4)withseedvalues:f0=0;f1=1CreateaFunctionthatImplementingtheN rstFibonacciNumbers[EndofExercise]Exercise6.3.4.PrimeNumbersThe rst25primenumbers(alltheprimenumberslessthan100)are:2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97Byde nitionaprimenumberhasboth1anditselfasadivisor.Ifithasanyotherdivisor,itcannotbeprime.Anaturalnumber(1,2,3,4,5,6,etc.)iscalledaprimenumber(oraprime)ifitisgreaterthan1andcannotbewrittenasaproductoftwonaturalnumbersthatarebothsmallerthanit.Tip!Iguessthiscanbeimplementedinmanydi erentways,butonewayistouse2nestedForLoops.64
CreateaPythonfunctionwhereyoucheckifagivennumberisaprimenumberornot.YoucancheckthefunctionintheCommandWindowlikethis:1number=42checkifprime(number)ThenPythonrespondwithTrueorFalse.[EndofExercise]65
Chapter7CreatingClassesinPython7.1IntroductionPythonisanobjectorientedprogramming(OOP)language.AlmosteverythinginPythonisanobject,withitspropertiesandmethods.Thefoundationforallobjectorientedprogramming(OOP)languagesareClasses.Tocreateaclass,usethekeywordclass:1classClassName:23.4.5.6Example7.1.1.SimpleClassExampleWewillcreateasimpleClassinPython.1classCar:2model=”Volvo”3color=”Blue”456car=Car()789print(car.model)10print(car.color)Listing7.1:SimplePythonClassTheresultswillbeinthiscase:1Volvo2Blue66
Thisexampledon’tillustratethegoodthingswithclassessowewillcreatesomemoreexamples.[EndofExample]Example7.1.2.PythonClassLetscreatethefollowingPythonCode:1classCar:2model=””3color=””45car=Car()67car.model=”Volvo”8car.color=”Blue”910print(car.color+””+car.model)1112car.model=”Ford”13car.color=”Green”1415print(car.color+””+car.model)Listing7.2:PythonClassexampleYoushouldtrytheseexamples.[EndofExample]7.2Theinit()FunctionInPythonallclasseshaveabuilt-infunctioncalledinit(),whichisalwaysexecutedwhentheclassisbeinginitiated.InmanyotherOOPlanguageswecallthistheConstructor.Exercise7.2.1.Theinit()FunctionWewillcreateasimpleexamplewhereweusetheinit()functiontoillustratetheprinciple.WechangeourpreviousCarexamplelikethis:1classCar:2definit(self,model,color):3self.model=model4self.color=color56car1=Car(“Ford”,”Green”)78print(car1.model)9print(car1.color)101167
12car2=Car(“Volvo”,”Blue”)1314print(car2.model)15print(car2.color)Listing7.3:PythonClassConstructorExampleLetsextendtheClassbyde ningaFunctionaswell:1#DefiningtheClassCar2classCar:3definit(self,model,color):4self.model=model5self.color=color67defdisplayCar(self):8print(self.model)9print(self.color)101112#LetsstartusingtheClass1314car1=Car(“Tesla”,”Red”)1516car1.displayCar()171819car2=Car(“Ford”,”Green”)2021print(car2.model)22print(car2.color)232425car3=Car(“Volvo”,”Blue”)2627print(car3.model)28print(car3.color)2930car3.color=”Black”3132car3.displayCar()Listing7.4:PythonClasswithFunctionAsyouseefromthecodewehavenowde nedaClass”Car”thathas2Classvariablescalled”model”and”color”,andinadditionwehavede nedaFunc-tion(orMethod)called”displayCar()”.Itsnormaltousetheterm”Method”forFunctionsthatarede nedwithinaClass.Youdeclareclassmethodslikenormalfunctionswiththeexceptionthatthe rstargumenttoeachmethodisself.Tocreateinstancesofaclass,youcalltheclassusingclassnameandpassinwhateverargumentsitsinit()methodaccepts.Forexample:68
1car1=Car(“Tesla”,”Red”)[EndofExample]Exercise7.2.2.CreatetheClassinaseparatePython leWestartbycreatingtheClassandthenwesavethecodein”Car.py”:1#DefiningtheClassCar2classCar:3definit(self,model,color):4self.model=model5self.color=color67defdisplayCar(self):8print(self.model)9print(self.color)Listing7.5:De nePythonClassinseparateFileThenwecreateaPythonScript(testCar.py)whereweareusingtheClass:1#ImportingtheCarClass2fromCarimportCar34#LetsstartusingtheClass56car1=Car(“Tesla”,”Red”)78car1.displayCar()91011car2=Car(“Ford”,”Green”)1213print(car2.model)14print(car2.color)151617car3=Car(“Volvo”,”Blue”)1819print(car3.model)20print(car3.color)2122car3.color=”Black”2324car3.displayCar()Listing7.6:ScriptthatisusingtheClassNoticethefollowinglineatthetop:1fromCarimportCar[language=Python][EndofExample]69
7.3ExercisesBelowyou nddi erentself-pacedExercisesthatyoushouldgothroughandsolveonyourown.TheonlywaytolearnPythonistodolotsofExercises!Exercise7.3.1.CreatePythonClassCreateaPythonClasswhereyoucalculatethedegreesinFahrenheitbasedonthetemperatureinCelsiusandviceversa.TheformulaforconvertingfromCelsiustoFahrenheitis:Tf=(Tc9=5)+32(7.1)TheformulaforconvertingfromFahrenheittoCelsiusis:Tc=(Tf32)(5=9)(7.2)[EndofExercise]70
Chapter8CreatingPythonModulesAsyourprogramgetslonger,youmaywanttosplititintoseveral lesforeasiermaintenance.Youmayalsowanttouseahandyfunctionthatyouhavewritteninseveralprogramswithoutcopyingitsde nitionintoeachprogram.Tosupportthis,Pythonhasawaytoputde nitionsina leandusetheminascriptorinaninteractiveinstanceoftheinterpreter(thePythonConsolewindow).8.1PythonModulesAmoduleisa lecontainingPythonde nitionsandstatements.The lenameisthemodulenamewiththesux.pyappended.PythonallowsyoutosplityourprogramintomodulesthatcanbereusedinotherPythonprograms.Itcomeswithalargecollectionofstandardmodulesthatyoucanuseasthebasisofyourprogramsaswehaveseenexamplesofinpreviouschapters.Notitistimetomakeyourownmodulesfromscratch.Consideramoduletobethesameasacodelibrary.A lecontainingasetoffunctionsyouwanttoincludeinyourapplication.Previouslyyouhavebeenusingdi erentmodules,librariesorpackagescreatedbythePythonorganizationorbyothers.Hereyouwillcreateyourownmodulesfromscratch.Example8.1.1.Createyour rstPythonModuleWewillcreateaPythonmodulewith2functions.The rstfunctionshouldconvertfromCelsiustoFahrenheitandtheotherfunctionshouldconvertfromFahrenheittoCelsius.TheformulaforconvertingfromCelsiustoFahrenheitis:Tf=(Tc9=5)+32(8.1)71
TheformulaforconvertingfromFahrenheittoCelsiusis:Tc=(Tf32)(5=9)(8.2)First,wecreateaPythonmodulewiththefollowingfunctions(fahrenheit.py):1defc2f(Tc):23Tf=(Tc9/5)+324returnTf567deff2c(Tf):89Tc=(Tf32)(5/9)10returnTcListing8.1:FahrenheitFunctionsThen,wecreateaPythonscriptfortestingthefunctions(testfahrenheit.py):1fromfahrenheitimportc2f,f2c23Tc=045Tf=c2f(Tc)67print(“Fahrenheit:”+str(Tf))8910Tf=321112Tc=f2c(Tf)1314print(“Celsius:”+str(Tc))Listing8.2:PythonScripttestingthefunctionsTheresultsbecomes:1Fahrenheit:32.02Celsius:0.08.2ExercisesBelowyou nddi erentself-pacedExercisesthatyoushouldgothroughandsolveonyourown.TheonlywaytolearnPythonistodolotsofExercises!Exercise8.2.1.CreatePythonModuleforconvertingbetweenradiansanddegreesSincemostofthetrigonometricfunctionsrequirethattheangleisexpressedinradians,wewillcreateourownfunctionsinordertoconvertbetweenradians72
anddegrees.Itisquiteeasytoconvertfromradianstodegreesorfromdegreestoradians.Wehavethat:2[radians]=360[degrees](8.3)Thisgives:d[degrees]=r[radians](180)(8.4)andr[radians]=d[degrees](180)(8.5)Createtwofunctionsthatconvertfromradianstodegrees(r2d(x))andfromdegreestoradians(d2r(x))respectively.ThesefunctionsshouldbesavedinonePython le.py.Testthefunctionstomakesurethattheyworkasexpected.Youcanchoosetomakeanew.py letotestthesefunctionsoryoucanusetheConsolewindow.[EndofExercise]73
Chapter9FileHandlinginPython9.1IntroductionPythonhasseveralfunctionsforcreating,reading,updating,anddeleting les.Thekeyfunctionforworkingwith lesinPythonistheopen()function.Theopen()functiontakestwoparameters;Filename,andMode.Therearefourdi erentmethods(modes)foropeninga le:”x”-Create-Createsthespeci ed le,returnsanerrorifthe leexists”w”-Write-Opensa leforwriting,createsthe leifitdoesnotexist”r”-Read-Defaultvalue.Opensa leforreading,errorifthe ledoesnotexist”a”-Append-Opensa leforappending,createsthe leifitdoesnotexistInadditionyoucanspecifyifthe leshouldbehandledasbinaryortextmode”t”-Text-Defaultvalue.Textmode”b”-Binary-Binarymode(e.g.images)9.2WriteDatatoaFileTocreateaNew leinPython,usetheopen()method,withoneofthefollowingparameters:”x”-Create-Createsthespeci ed le,returnsanerrorifthe leexists”w”-Write-Opensa leforwriting,createsthe leifitdoesnotexist”a”-Append-Opensa leforappending,createsthe leifitdoesnotexist74
TowritetoanExisting le,youmustaddaparametertotheopen()function:”w”-Write-Opensa leforwriting,createsthe leifitdoesnotexist”a”-Append-Opensa leforappending,createsthe leifitdoesnotexistExample9.2.1.WriteDatatoaFile1f=open(“myfile.txt”,”x”)23data=”HeloWorld”45f.write(data)67f.close()Listing9.1:WriteDatatoaFile[EndofExample]9.3ReadDatafromaFileToreadtoanexisting le,youmustaddthefollowingparametertotheopen()function:”r”-Read-Defaultvalue.Opensa leforreading,errorifthe ledoesnotexistExample9.3.1.ReadDatafromaFile1f=open(“myfile.txt”,”r”)23data=f.read()45print(data)67f.close()Listing9.2:ReadDatafromaFile[EndofExample]9.4LoggingDatatoFileTypicallyyouwanttowritemultipledatatothe,e.g.,assumeyoureadsometemperaturedataatregularintervalsandthenyouwanttosavethetemperaturevaluestoaFile.Example9.4.1.LoggingDatatoFile75
1data=[1.6,3.4,5.5,9.4]23f=open(“myfile.txt”,”x”)45forvalueindata:6record=str(value)7f.write(record)8f.write(“nn”)910f.close()Listing9.3:LoggingDatatoFile[EndofExample]Example9.4.2.ReadLoggedDatafromFile1f=open(“myfile.txt”,”r”)23forrecordinf:4record=record.replace(“nn”,””)5print(record)67f.close()Listing9.4:ReadLoggedDatafromFile[EndofExample]9.5WebResourcesBelowyou nddi erentusefulresourcesforFileHandling.PythonFileHandling-w3school:https://www.w3schools.com/python/pythonfilehandling:aspReadingandWritingFiles-python.org:https://docs.python.org/3/tutorial/inputoutput.htmlreading-and-writing- les9.6ExercisesBelowyou nddi erentself-pacedExercisesthatyoushouldgothroughandsolveonyourown.TheonlywaytolearnPythonistodolotsofExercises!Exercise9.6.1.DataLoggingAssumeyouhavethefollowingdatayouwanttologtoaFileasshowninTable9.1.LogthesedatatoaFile.CreateanotherPythonScriptthatreadsthesamedata.76
[EndofExercise]Exercise9.6.2.DataLogging2AssumeyoureaddatafromaTemperaturesensorevery10secondsforaperiodofletsay5minutes.LogthedatatoaFile.YoucanusetheRandomGeneratorinPython.AnexampleofhowtousetheRandomGeneratorisshownbelow:1importrandom2forxinrange(10):3data=random.randint(1,31)4print(data)Listing9.5:ReadDatafromaFileMakesuretologboththetimeandthetemperaturevalueCreateanotherPythonScriptthatreadsthesamedata.YoushouldalsoplotthedatayoureadfromtheFile.[EndofExercise]77
Table9.1:LoggedDataTimeValue122225328……78
Chapter10ErrorHandlinginPython10.1IntroductiontoErrorHandlingSofarerrormessageshaven’tbeendiscussed.Youcouldsaythatwehave2kindsoferrors:syntaxerrorsandexceptions.10.1.1SyntaxErrorsBelowweseeanexampleofsyntaxerrors:1>>>print(HelloWorld)2File”“,line13print(HelloWorld)4^5SyntaxError:invalidsyntaxIntheexamplewehavewrittenprint(HelloWorld)insteadofprint(“HelloWorld”)andthenthePythonInterpretergivesusanerrormessage.10.1.2ExceptionsEvenifastatementorexpressionissyntacticallycorrect,itmaycauseanerrorwhenanattemptismadetoexecuteit.Errorsdetectedduringexecutionarecalledexceptionsandarenotunconditionallyfatal:youwillsoonlearnhowtohandletheminPythonprograms.Mostexceptionsarenothandledbyprograms,however,andresultinerrormessagesasshownhere:1>>>10(1/0)2Traceback(mostrecentcalllast):34File”“,line1,in510(1/0)67ZeroDivisionError:divisionbyzeroor:1>>>’2’+22Traceback(mostrecentcalllast):379
4File”“,line1,in5’2’+267TypeError:mustbestr,notint10.2ExceptionsHandlingItispossibletowriteprogramsthathandleselectedexceptions.InPythonwecanusethefollowingbuilt-inExceptionsHandlingfeatures:Thetryblockletsyoutestablockofcodeforerrors.Theexceptblockletsyouhandletheerror.The nallyblockletsyouexecutecode,regardlessoftheresultofthetry-andexceptblocks.Whenanerroroccurs,orexceptionaswecallit,Pythonwillnormallystopandgenerateanerrormessage.Theseexceptionscanbehandledusingthetry-exceptstatements.Somebasicexample:1try:210(1/0)3except:4print(“Thecalculationfailed”)or:1try:2print(x)3except:4print(“xisnotdefined”)Youcanalsousemultipleexceptions:1try:2print(x)3exceptNameError:4print(“xisnotdefined”)5except:6print(“Somethingiswrong”)The nallyblock,ifspeci ed,willbeexecutedregardlessifthetryblockraisesanerrorornot.Example:80
1x=223try:4print(x)5exceptNameError:6print(“xisnotdefined”)7except:8print(“Somethingiswrong”)9finally:10print(“TheProgramisfinished”)Ingeneralyoushouldusetry-except- nallywhenyoutrytoopenaFile,readorwritetoFiles,connecttoaDatabase,etc.Example:1try:2f=open(“myfile.txt”)3f.write(“LorumIpsum”)4except:5print(“Somethingwentwrongwhenwritingtothefile”)6finally:7f.close()81
Chapter11DebugginginPythonDebuggingistheprocessof ndingandresolvingdefectsorproblemswithinacomputerprogramthatpreventcorrectoperationofcomputersoftwareorasystem[14].Debuggersaresoftwaretoolswhichenabletheprogrammertomonitortheex-ecutionofaprogram,stopit,restartit,setbreakpoints,andchangevaluesinmemory.Thetermdebuggercanalsorefertothepersonwhoisdoingthede-bugging.Asaprogrammer,oneofthe rstthingsthatyouneedforseriousprogramdevelopmentisadebugger.Pythonhasabuilt-indebuggerthatcanbeusedifyouarecodingPythonwithabasictexteditorandrunningyourPythonprogramsfromthecommandline.AbetteroptionistousetheDebuggingfeaturesintegratedinyourPythonEd-itor.DebuggingistypicallyintegratedwiththePythonEditoryouareusing.Seethespeci cchapterforthedi erentPythonEditors.82
Chapter12InstallingandusingPythonPackagesApackagecontainsallthe lesyouneedforamodule.ModulesarePythoncodelibrariesyoucanincludeinyourproject.SincePythonisopensourceyoucan ndthousandsofPythonPackagesthatyoucaninstallanduseinyourPythonprograms.YoucanuseaPythonDistributionlikeAnacondaDistribution(orsimilarPythonDistributions)todownloadandinstallmanycommonPythonPack-agesasmentionedpreviously.12.1WhatisPIP?PIPisapackagemanagerforPythonpackages,ormodulesifyoulike.PIPisatoolforinstallingPythonpackages.IfyoudonothavePIPinstalled,youcandownloadandinstallitfromthispage:https://pypi.org/project/pip/PIPistypicallyusedfromtheCommandPrompt(Windows)orTerminalwin-dow(macOS).InstallingPythonPackages:1pipinstallpackagenameUninstallingPythonPackages:1pipuninstallpackagenameSomePythonEditorsalsohaveagraphicalwayofinstallingPythonPackages,like,e.g.,VisualStudio.83
PartIIIPythonEnvironmentsandDistributions84
Chapter13IntroductiontoPythonEnvironmentsandDistributionsPythoncomeswithmany
avoursandversion.PythonisopensourceandeverybodycanbundleanddistributePythonanddi erentPythonPackages.APythonenvironmentisacontextinwhichyourunPythoncodeandincludesPythonPackages.Anenvironmentconsistsofaninterpreter,alibrary(typicallythePythonStan-dardLibrary),andasetofinstalledpackages.Thesecomponentstogetherdeterminewhichlanguageconstructsandsyntaxarevalid,whatoperating-systemfunctionalityyoucanaccess,andwhichpack-agesyoucanuse.YoucanhavemultiplePythonEnvironmentsonyourComputer.Someofthemare:CPythondistributionavailablefrompython.orgAnacondaEnthoughtCanopyWinPythonetc.ItiseasytostartusingPythonbyinstallingoneofthesePythonDistributions.85
ButyoucanalsoinstallthecorePythonfrom:https://www.python.orgTheninstalltheadditionalPythonPackagesyouneedbyusingPIP.https://pypi.org/project/pip/13.1PackageandEnvironmentManagersThetwomostpopulartoolsforinstallingPythonPackagesandsettingupPythonenvironmentsare:PIP-aPythonPackageManagerConda-aPackageandEnvironmentManager(forPythonandotherlan-guages)13.1.1PIPWeb:https://pypi.orgPIPistypicallyusedfromtheCommandPrompt(Windows)orTerminalwin-dow(macOS).InstallingPythonPackages:1pipinstallpackagenameUninstallingPythonPackages:1pipuninstallpackagename13.1.2CondaCondaisanopensourcepackagemanagementsystemandenvironmentman-agementsystemthatrunsonWindows,macOSandLinux.Condainstalls,runsandupdatespackagesandtheirdependencies.TheCondapackageandenvironmentmanagerisincludedinallversionsofAna-conda.CondawascreatedforPythonprograms,butitcanpackageanddistributesoft-wareforanylanguage.Condaallowsyoutotoalsocreateseparateenvironmentscontaining les,pack-agesandtheirdependenciesthatwillnotinteractwithotherenvironments.86
Web:https://conda.io/CondaispartoforintegratedwiththeAnacondaPythonDistribution.Web:https://www.anaconda.com13.2PythonVirtualEnvironmentsPython”VirtualEnvironments”allowPythonpackagestobeinstalledinanisolatedlocationforaparticularapplication,ratherthanbeinginstalledglob-ally.YoucanhavemultiplePythonEnvironmentsonyourcomputer.PythonVirtualEnvironmentshavetheirowninstallationdirectoriesandtheydon’tsharelibrarieswithothervirtualenvironments.Python”VirtualEnvironments”ishandywhenyouhavedi erentPythonappli-cationsthatneedsdi erentversionsofPythonordi erentversionofthePythonPackagesyouareusing.87
Chapter14AnacondaAnacondaisnotanEditor,butaPythonDistributionpackage.Spyderisin-cludedinthePythonDistributionpackage.YoucanalsouseAnacondatoinstallotherEditorsorPythonpackages.ItisavailableforWindows,macOSandLinux.Web:https://www.anaconda.comWikipedia:https://en.wikipedia.org/wiki/Anaconda(Pythondistribution)14.1AnacondaNavigatorAnacondaNavigatorisadesktopgraphicaluserinterface(GUI)includedinAnacondadistributionthatallowsuserstolaunchapplicationsandmanagePythonpackages.TheAnacondaNavigatorcansearchforpackagesandinstallthemonyourcomputer,runthepackagesandupdatethem.Figure14.1showstheAnacondaNavigator.88
Figure14.1:AnacondaNavigator89
Chapter15EnthoughtCanopyEnthoughtCanopyisaPythonPlatformorPythonDistributionforScientistsandEngineers.ItisavailableforWindows,macOSandLinux.CanopyisfreelyavailabletoallusersundertheCanopylicense.Canopypro-videsaccesstoseveralhundredsPythonpackages,includingNumPy,SciPy,Pandas,Matplotlib,andIPython.Inaddition,wehavetheCanopyPythonEditor.EnthoughtCanopyisacompetitortotheAnacondaPythonDistribution.Itisamatteroftastewhoyouprefer.Web:https://www.enthought.com/product/canopy/90
PartIVPythonEditors91
Chapter16PythonEditorsAnEditorisaprogramwhereyoucreateyourcode(andwhereyoucanrunandtestit).MostEditorshavealsofeaturesforDebuggingandIntelliSense.Intheory,youcanuseWindowsNotepadforcreatingPythonprograms,butinpracticeitisimpossibletocreateprogramswithouthavinganeditorwithDebugging,IntelliSense,colorformatting,etc.ForsimplePythonprogramsyoucanusetheIDLEEditor,butformoread-vancedprogramsabettereditorisrecommended.ExamplesofPythonEditors:SpyderVisualStudioCodeVisualStudioPyCharmWingJupyterNotebookWewillgiveanoverviewoftheseCodeEditorsinthenextchapters.Iguesshundredsofdi erenteditorscanbeusedforPythonProgramming,ei-theroutoftheboxorifyouinstallanadditionalExtensionthatmakessureyoucanusePythoninthateditor.IfyoualreadyhaveafavoriteCodeEditor,itisagoodchangeyoucanusethatoneforPythonprogramming.Whicheditoryoushouldusedependsonyourbackground,whatkindofcodeeditorsyouhaveusedpreviously,yourprogrammingskills,whatyouraregoingtodevelopinPython,etc.92
IfyouarefamiliarwithMATLAB,Spyderisrecommended.Also,ifyouwanttousePythonfornumericalcalculationsandcomputations,Spyderisagoodchoice.IfyouwanttocreateWebApplicationsorotherkindsofApplications,otherEditorsareprobablybettertouse.Foralistof”BestPythonEditors”,see[15].93
Chapter17SpyderSpyder-shortfor”Scienti cPYthonDevelopmentEnviRonment”.Spyderisanopensourcecross-platformintegrateddevelopmentenvironment(IDE)forscienti cprogramminginthePythonlanguage.Figure17.1:SpyderEditorTheSpydereditorconsistsofthefollowingpartsorwindows:CodeEditorwindowiPythonConsolewindow94
VariableExploreretc.Web:https://www.spyder-ide.orgIfyouhaveusedMATLABpreviouslyorwanttousePythonforscienti cuse,Spyderisagoodchoice.itiseasytoinstallusingtheAnacondaDistribution.Web:https://www.anaconda.com95
Chapter18VisualStudioCode18.1IntroductiontoVisualStudioCodeVisualStudioCodeisasimpleandeasytouseeditorthatcanbeusedformanydi erentprogramminglanguages.Figure18.1:UsingVisualStudioCodeasPythonEditorRight-Clickandselect”RunPythonFileinTerminal”Web:https://code.visualstudio.comWikipedia:https://en.wikipedia.org/wiki/VisualStudioCode96
18.2PythoninVisualStudioCodeInadditiontoVisualStudioCodeyouneedtoinstallthePythonextensionforVisualStudioCode.YoumustinstallaPythoninterpreteryourselfseparatelyfromtheextension.Foraquickinstall,usePythonfrompython.org.https://www.python.orgPythonisaninterpretedlanguage,andinordertorunPythoncodeandgetPythonIntelliSensewithinVisualStudioCode,youmusttellVisualStudioCodewhichinterpretertouse.Web:https://code.visualstudio.com/docs/languages/python97
Chapter19VisualStudio19.1IntroductiontoVisualStudioMicrosoftVisualStudioisanintegrateddevelopmentenvironment(IDE)fromMicrosoft.Itisusedtodevelopcomputerprograms,aswellaswebsites,webapps,webservicesandmobileapps.Thedefault(main)programminglanguageinVisualstudioisC,butmanyotherprogramminglanguagesaresupported.YoucouldsayVisualStudioisthebigbrotherofVisualStudioCode.VisualstudioisavailableforWindowsandmacOS.VisualStudio(from2017),hasintegratedsupportforPython,itiscalled”PythonSupportinVisualStudio”.Web:https://visualstudio.microsoft.comWikipedia:https://en.wikipedia.org/wiki/MicrosoftVisualStudioGotomyWebSitetolearnmoreaboutVisualStudioandCprogramming:https://www.halvorsen.blog/VisualStudioandC:https://www.halvorsen.blog/documents/programming/csharp/19.2WorkwithPythoninVisualStudioWorkwithPythoninVisualStudio:https://docs.microsoft.com/visualstudio/python/98
Figure19.1:UsingVisualStudioasPythonEditor19.2.1MakeVisualStudioreadyforPythonProgram-mingVisualStudioismainlyforWindows.AMacOSversionofVisualStudiodoexists,butithaslotlessfeaturesthantheWindowsedition.NotethatPythonsupportisavailableonlyonVisualStudioforWindows.IfyouuseMacandLinux,youneedtouseVisualStudioCode.YoucouldsayVisualStudioCodeisadown-scaledversionofVisualStudio.VisualStudio(from2017),hasintegratedsupportforPython,itiscalled”PythonSupportinVisualStudio”.Evenifitisintegrated,youneedtomanu-allyselectwhichcomponentsyouwanttoinstallonyourcomputer.MakesuretodownloadandrunthelatestVisualStudio2017installerforWindows.whenyouruntheVisualStudioinstaller(eitherforthe rsttimeorifyoualreadyhaveinstalledVisualStudio2017andwanttomodifyit)thewindowshowninFigure19.2popsup.Theinstallerpresentsyouwithalistofsocalledworkloads,whicharegroupsofrelatedoptionsforspeci cdevelopmentareas.ForPython,selectthe”Pythondevelopment”workloadandselectInstall(Figure19.3).19.2.2PythonInteractiveToquicklytestPythonsupport,launchVisualStudio,pressAlt+I(orselectfromthemenu:Tools-Python-PythonInteractiveWindow)toopenthePythonInteractivewindow.SeeFigure19.4.Letswritesomethinglikethis:1>>>a=299
Figure19.2:InstallingPythonExtensionforVisualStudioFigure19.3:PythonDevelopmentWorkload2>>>b=53>>>x=34>>>y=ax+b5>>>y19.2.3NewPythonProjectLetsseehowwecancreateaPythonApplication.Startbyselectfromthemenu:File-New-Project…TheNewProjectwindowpopsup.SeeFigure19.5.WecancreateanordinaryPythonApplication(oneormorePythonScripts),wecanchoosetocreateaWebApplicationusingeitherWebFrameworkslikeDjangoorFlask,orwecancreatedi erentDesktopGUIapplications.WecanalsocreateGames.Example19.2.1.PythonHelloWorldApplicationinVisualStudio100
Figure19.4:PythonInteractiveWestartbycreatingabasicHelloWorldPythonApplication.SeeFigure19.1.SelectFile-New-Project…TheNewProjectwindowpopsup.SeeFigure19.5.Nametheproject,e.g,”PythonApplication1″.IntheProjectExplorer,openthe”PythonApplication1.py” leandenterthefollowingPythoncode:1print(“HelloWorld”)HitF5(ourclickthegreenarrow)inordertorunorexecutethePythonprogram.Youcanalsorightclickonthe leandselect”StartwithoutDebugging”.[EndofExample]Example19.2.2.VisualStudioPythonPlottingCreateanewPythonFilebyrightclickintheSolutionExplorerandselectAdd-NewItem…andthenselect”EmptyPythonFile”.EnterthefollowingPythonCode:1importmatplotlib.pyplotasplt2importnumpyasnp34xstart=05xstop=2np.pi6increment=0.178x=np.arange(xstart,xstop,increment)910y=np.sin(x)1112plt.plot(x,y)13plt.title(‘y=sin(x)’)101
Figure19.5:NewPythonProject14plt.xlabel(‘x’)15plt.ylabel(‘y’)16plt.grid()17plt.axis([0,2np.pi,1,1])18plt.show()SeealsoFigure19.6.MakesuretoselectproperPythonEnvironment.SeeFigure(19.7).VisualStudiosupportsmultiplePythonEnvironments.InthisexampleweusetheMatplotlibpackageforplotting,soweneedtohavethatpackageinstalledonthecomputer.YoucaninstalltheMatplotlibpackageindi erentPythonEnvironments.IhaveinstalledtheMatplotlibpackageaspartoftheAnacondadistributionsetup,soIselect”Anacondax.x.x”inthePythonEnvironmentswindow.Ifyouhaven’tinstalledtheMatplotlibpackageyet(eitheraspartofAnacondaormanuallyusingPIP),youcanalsoeasilyinstallPythonpackagesfromVisualstudio.SeeFigure19.8.YoucanalsoeasilyseewhichPythonPackagesthatareinstalledforthedi er-entPythonEnvironments.SeeFigure19.9.102
Figure19.6:PythonPlottingExamplewithVisualStudioThegoodthingaboutusingVisualStudioisthatyouhaveagraphicaluserinterfaceforeverything,youdon’tneedtousetheCommandwindowetc.forinstallingPythonPackages,etc.HitF5(ourclickthegreenarrow)inordertorunorexecutethePythonprogram.Youcanalsorightclickonthe leandselect”StartwithoutDebugging”.Wegetthefollowingresults,seeFigure19.10.[EndofExample]103
Figure19.7:SelectyourPythonEnvironmentFigure19.8:InstallPythonPackagesfromVisualStudio104
Figure19.9:InstallingPythonPackagesfordi erentPythonEnvironmentsfromVisualStudioFigure19.10:PythonPlottingExamplewithVisualStudio105
Chapter20PyCharmPyCharmiscross-platform,withWindows,macOSandLinuxversions.TheCommunityEditionisfreetouse,whiletheProfessionalEdition(paidversion)hassomeextrafeatures.ThePyCharmEditorisshowninFigure20.1.Figure20.1:PyCharmPythonEditorWeb:https://www.jetbrains.com/pycharm/Wikipedia:https://en.wikipedia.org/wiki/PyCharmAnacondaandJetBrainsalsohaveacollaborationando erwhattheycallPy-CharmforAnaconda.Youcandownloadithere:106
https://www.jetbrains.com/pycharm/promo/anaconda/WehavecodeeditorslikeVisualStudioandVisualStudioCodewhichcanbeusedformanydi erentprogramminglanguagesbyinstallingdi erenttypesofplugins.EditorslikeSpyderandPyCharmaretailor-madeeditorsforthePythonlan-guage.Spyderislight-weightIDEtypicallyusedforscienti cuse.PyCharmontheotherhandisfull-blownIDEforsoftwaredevelopmentingeneralbyusingthePythonlanguage.Itsupportsmanyplugins,it’seasiertoprogramDjango,etc.107
Chapter21WingPythonIDETheWingPythonIDEfamilyofintegrateddevelopmentenvironments(IDEs)fromWingwarewerecreatedspeci callyforthePythonprogramminglanguage.3di erentversionofWingexists[12]:Wing101{averysimpli edfreeversion,forteachingbeginningpro-grammersWingPersonal{freeversionthatomitssomefeatures,forstudentsandhobbyistsWingPro{afull-featuredcommercial(paid)version,forprofessionalprogrammersFigure21.1:WingPythonIDEWeb:https://wingware.com108
Wikipedia:https://en.wikipedia.org/wiki/WingIDE109
Chapter22JupyterNotebookTheJupyterNotebookisanopen-sourcewebapplicationthatallowsyoutocre-ateandsharedocumentsthatcontainlivecode,equations,visualizationsandtext.TheNotebookhassupportforover40programminglanguages,includingPython.Figure22.1:JupyterNotebook[16]Web:http://jupyter.orgWikipedia:https://en.wikipedia.org/wiki/ProjectJupyter110
22.1JupyterHubJupyterHubisamulti-userversionofthenotebookdesignedforcompanies,classroomsandresearchlabs[17].JupyterHubrunsinthecloudoronyourownhardware.JupyterHubisopen-sourceanddesignedtoberunonavarietyofinfrastructure.Thisincludescommercialcloudproviders,virtualmachines,orevenyourownlaptophardware.Web:http://jupyter.org/hub22.2MicrosoftAzureNotebooksMicrosoftAzureNotebooksisaversionofJupyterNotebookfromMicrosoft.ThegoodthingaboutMicrosoftAzureNotebooksisthatyouhavetheinfras-tructureandeverythingupandrunningreadyforyoutouse.Youcanuseitforfreeaswell.Web:https://notebooks.azure.comExample22.2.1.ExampleNameFigure22.2showsanoverviewofmyAzureNotebookProjects.Figure22.2:AzureNotebookProjectsFigure22.3showsanoverviewofmyAzureNotebookProjectNotebooks.Figure22.4showsanexampleofasimpleNotebook.[EndofExample]111
Figure22.3:AzureNotebookProjectNotebooksFigure22.4:AzureNotebookExample112
PartVPythonforMathematicsApplications113
Chapter23MathematicsinPythonPythonisapowerfultoolformathematicalcalculations.IfyouarelookingforsimilarusingMATLAB,pleasetakealookatthesere-sources:https://www.halvorsen.blog/documents/programming/matlab/23.1BasicMathFunctionsThePythonStandardLibraryconsistsofdi erentmodulesforhandling leI/O,basicmathematics,etc.Youdon’tneedtoinstalltheseseparately,butyouneedtoimportantthemwhenyouwanttousesomeofthesemodulesorsomeofthefunctionswithinthesemodules.InthischapterwewillfocusonthemathmodulethatispartofthePythonStandardLibrary.Themathmodulehasallthebasicmathfunctionsyouneed,suchas:Trigono-metricfunctions:sin(x),cos(x),etc.Logarithmicfunctions:log(),log10(),etc.Constantslikepi,e,inf,nan,etc.etc.Example23.1.1.UsingthemathmoduleWecreatesomebasicexampleshowtouseaLibrary,aPackageoraModule:Ifweneedonlythesin()functionwecandolikethis:1frommathimportsin23x=3.144y=sin(x)56print(y)Ifweneedafewfunctionswecandolikethis114
1frommathimportsin,cos23x=3.144y=sin(x)5print(y)67y=cos(x)8print(y)Ifweneedmanyfunctionswecandolikethis:1frommathimport23x=3.144y=sin(x)5print(y)67y=cos(x)8print(y)Wecanalsousethisalternative:1importmath23x=3.144y=math.sin(x)56print(y)Wecanalsowriteitlikethis:1importmathasmt23x=3.144y=mt.sin(x)56print(y)[EndofExample]Thereareadvantagesanddisadvantageswiththedi erentapproaches.Inyourprogramyoumayneedtousefunctionsfrommanydi erentmodulesorpack-ages.Ifyouimportthewholemoduleinsteadofjustthefunction(s)youneedyouusemoreofthecomputermemory.Veryoftenwealsoneedtoimportandusemultiplelibrarieswherethedi erentlibrarieshavesomefunctionswiththesamenamebutdi erentuse.OtherusefulmodulesinthePythonStandardLibraryarestatistics(whereyouhavefunctionslikemean(),stdev(),etc.)FormoreinformationaboutthefunctionsinthePythonStandardLibrary,see:https://docs.python.org/3/library/115
23.1.1ExercisesBelowyou nddi erentself-pacedExercisesthatyoushouldgothroughandsolveonyourown.TheonlywaytolearnPythonistodolotsofExercises!Exercise23.1.1.CreateMathematicalExpressionsinPythonCreateafunctionthatcalculatesthefollowingmathematicalexpression:z=3×2+px2+y2+eln(x)(23.1)Testwithdi erentvaluesforxandy.[EndofExercise]Exercise23.1.2.CreateadvancedMathematicalExpressionsinPythonCreatethefollowingexpressioninPython:f(x)=ln(ax2+bx+c)sin(ax2+bx+c)4x2+cos(x2)(ax2+bx+c)(23.2)Givena=1;b=3;c=5Findf(9)(Theanswershouldbef(9)=0:0044)Tip!Youshouldsplittheexpressionsintodi erentparts,suchas:poly=ax2+bx+cnum=:::den=:::f=:::Thismakestheexpressionsimplertoreadandunderstand,andyouminimizetheriskofmakinganerrorwhiletypingtheexpressioninPython.Whenyougotthecorrectanswertrytochangeto,e.g.,a=2;b=8;c=6Findf(9)[EndofExercise]Exercise23.1.3.Pythagoras116
Figure23.1:Right-angledtrianglePythagorastheoremisasfollows:c2=a2+b2(23.3)CreateafunctionthatusesPythagorastocalculatethehypotenuseofaright-angledtriangle(Figure23.1),e.g.:1defpythagoras(a,b)2…3…4returnc[EndofExercise]Exercise23.1.4.AlbertEinsteinGiventhefamousequationfromAlbertEinstein:E=mc2(23.4)Thesunradiates385x1024J=sofenergy.Calculatehowmuchofthemassonthesunisusedtocreatethisenergyperday.Howmanyyearswillittaketoconvertallthemassofthesuncompletely?Doweneedtoworryifthesunwillbeusedupinourgenerationorthenext?justifytheanswer.Themassofthesunis2x1030kg.117
[EndofExercise]Exercise23.1.5.CylinderSurfaceAreaCreateafunctionthat ndsthesurfaceareaofacylinderbasedontheheight(h)andtheradius(r)ofthecylinder.SeeFigure??.Figure23.2:cylinder[EndofExercise]23.2Statistics23.2.1IntroductiontoStatisticsMeanoraverage:Themeanisthesumofthedatadividedbythenumberofdatapoints.Itiscommonlycalled\theaverage”,Formulaformean:x=x1+x2+x3+:::+xNN=1NNXi=1xi(23.5)Example23.2.1.MeanGiventhefollowingdataset:2.2,4.5,6.2,3.6,2.6Mean:x=1NNXi=1xi=2:2+4:5+6:2+3:6+2:65=19:15=3:82(23.6)118
[EndofExample]Variance:Varianceisameasureofthevariationinadataset.var(x)=1NNXi=1(xix)2(23.7)Standarddeviation:Thestandarddeviationisameasureofthespreadofthevaluesinadatasetorthevalueofarandomvariable.Itisde nedasthesquarerootofthevariance.std(x)==pvar=vuut1NNXi=1(xix)2(23.8)Wetypicallyusethesymbolforstandarddeviation.Wehavethat2=var(x)23.2.2StatisticsfunctionsinPythonMathematicalstatisticsfunctionsinPython:https://docs.python.org/3/library/statistics.htmlstatisticsispartoftheThePythonStandardLibrary.FormoreinformationaboutthefunctionsinthePythonStandardLibrary,see:https://docs.python.org/3/library/Example23.2.2.StatisticsusingthestatisticsmoduleinPythonStandardLibraryBelowyou ndsomeexampleshowtousesomeofthestatisticsfunctionsinthestatisticsmoduleinPythonStandardLibrary:1importstatisticsasst23data=[1.0,2.5,3.25,5.75]45#MeanorAverage6m=st.mean(data)7print(m)89#StandardDeviation10stdev=st.stdev(data)119
11print(stdev)1213#Median14med=st.median(data)15print(med)1617#Variance18var=st.variance(data)19print(var)Listing23.1:StatisticsfunctionsinPython[EndofExample]IMPORTANT:Donotnameyour le”statistics.py”sincetheimportwillbeconfusedandthrowtheerrorsofthelibrarynotexistingandthemeanfunctionnotexisting.YoucanalsousetheNumPyLibrary.NumPyisthefundamentalpackageforscienti ccomputingwithPython.Hereyou ndanoverviewoftheNumPylibrary:http://www.numpy.orgExample23.2.3.StatisticsusingtheNumPyLibraryBelowyou ndsomeexampleshowtousesomeofthestatisticsfunctionsinNumPy:1importnumpyasnp23data=[1.0,2.5,3.25,5.75]45#MeanorAverage6m=np.mean(data)7print(m)89#StandardDeviation10stdev=np.std(data)11print(stdev)1213#Median14med=np.median(data)15print(med)1617#MinimumValue18minv=np.min(data)19print(minv)2021#MaxumumValue22maxv=np.max(data)23print(maxv)Listing23.2:StatisticsusingtheNumPyLibrary120
[EndofExample]Exercise23.2.1.CreateyourownStatisticsModuleinPythonUsingthebuilt-infunctionsinthePythonStandardLibraryortheNumPyli-braryisstraightforward.Inordertogetadeeperunderstandingofthemathematicsbehindthesefunc-tionsandtolearnmorePythonprogramming,youshouldcreateyourownStatisticsModuleinPython.CreateyourownStatisticsModuleinPython(e.g.,”mystatistics.py)andthencreateaPythonScript(e.g.,”testmystatistics.py)whereyoutestthesefunc-tions.Youshouldatleastimplementfunctionsformean,variance,standarddeviation,minimumandmaximum.[EndofExercise]23.3TrigonometricFunctionsPythono erslotsofTrigonometricfunctions,e.g.,sin,cos,tan,etc.Note!Mostofthetrigonometricfunctionsrequirethattheangleisexpressedinradians.Example23.3.1.TrigonometricFunctionsinMathmodule1importmathasmt23x=2mt.pi45y=mt.sin(x)6print(y)78y=mt.cos(x)9print(y)1011y=mt.tan(x)12print(y)Listing23.3:TrigonometricFunctionsinMathmoduleHerewehaveusedtheMathmoduleinthePythonStandardLibrary.FormoreinformationaboutthefunctionsinthePythonStandardLibrary,see:https://docs.python.org/3/library/index.html121
[EndofExample]Example23.3.2.PlottingTrigonometricFunctionsIntheexampleaboveweusedsomeofthetrigonometricfunctiosninbasiccal-culations.Letsseeifweareabletoplotthesefunctions.1importmathasmt2importmatplotlib.pyplotasplt34xdata=[]5ydata=[]67forxinrange(0,10):8xdata.append(x)9y=mt.sin(x)10ydata.append(y)1112plt.plot(xdata,ydata)13plt.show()Listing23.4:PlottingTrigonometricFunctionsIntheexamplewehaveplottedsin(x),wecaneasilyextendtheprogramtoplotcos(x),etc.FormoreinformationaboutthefunctionsinthePythonStandardLibrary,see:https://docs.python.org/3/library/index.html[EndofExample]Example23.3.3.TrigonometricFunctionsusingNumPyTheproblemwithusingtheTrigonometricfunctionsinthetheMathmodulefromthePythonStandardLibraryisthattheydon’thandleanarrayasinput.WewillusetheNumPylibraryinsteadbecausetheyhandlearrays,inadditiontoallthehandyfunctionalityintheNumPylibrary.1importnumpyasnp2importmatplotlib.pyplotasplt34xstart=05xstop=2np.pi6increment=0.178x=np.arange(xstart,xstop,increment)910y=np.sin(x)122
11plt.plot(x,y)12plt.title(‘y=sin(x)’)13plt.xlabel(‘x’)14plt.ylabel(‘y’)15plt.grid()16plt.axis([0,2np.pi,1,1])17plt.show()1819y=np.cos(x)20plt.plot(x,y)21plt.title(‘y=cos(x)’)22plt.xlabel(‘x’)23plt.ylabel(‘y’)24plt.grid()25plt.axis([0,2np.pi,1,1])26plt.show()2728y=np.tan(x)29plt.plot(x,y)30plt.title(‘y=tan(x)’)31plt.xlabel(‘x’)32plt.ylabel(‘y’)33plt.grid()34plt.axis([0,2np.pi,1,1])35plt.show()Listing23.5:TrigonometricFunctionsusingNumPyThisPythonscriptgivestheplotsasshowninFigure23.3.[EndofExample]Exercise23.3.1.CreatePythonfunctionsforconvertingbetweenradiansandegreesSincemostofthetrigonometricfunctionsrequirethattheangleisexpressedinradians,wewillcreateourownfunctionsinordertoconvertbetweenradiansanddegrees.Itisquiteeasytoconvertfromradianstodegreesorfromdegreestoradians.Wehavethat:2[radians]=360[degrees](23.9)Thisgives:d[degrees]=r[radians](180)(23.10)andr[radians]=d[degrees](180)(23.11)Createtwofunctionsthatconvertfromradianstodegrees(r2d(x))andfromdegreestoradians(d2r(x))respectively.123
ThesefunctionsshouldbesavedinonePython le.py.Testthefunctionstomakesurethattheyworkasexpected.[EndofExercise]Exercise23.3.2.TrigonometricfunctionsonrighttriangleGivenrighttriangleasshowninFigure23.4.Createafunctionthat ndstheangleA(indegrees)basedoninputarguments(a,c),(b,c)and(a,b)respectively.Use,e.g.,athirdinput\type”tode nethedi erenttypesabove.Useyoupreviousfunctionr2d()tomakesuretheoutputofyourfunctionisindegreesandnotinradians.Testthefunctiontomakesureitworksproperly.Tip!Wehavethat:sin(A)=ac!A=arcsin(ac)(23.12)cos(A)=bc!A=arccos(bc)(23.13)tan(A)=ab!A=arctan(ab)(23.14)WemayalsoneedtousethePythagoras’theorem:c2=a2+b2(23.15)1>>>a=52>>>b=83>>>c=sqrt(a2+b2)45>>>A=righttriangle(a,c,’sin’)6A=732.005489>>>A=righttriangle(b,c,’cos’)10A=1132.005412>>>A=righttriangle(a,b,’tan’)13A=1432.0054Wealsoseethattheanswerinthiscaseisthesame,whichisexpected.124
[EndofExercise]Exercise23.3.3.LawofCosinesGiventhetriangleasshowninFigure23.5.Createafunctionwhereyou ndcusingthelawofcosines.c2=a2+b22abcos(C)(23.16)Testthefunctionstomakesureitworksproperly.[EndofExercise]Exercise23.3.4.PlottingTrigonometricFunctionsPlotsin()andcos()for02inthesameplot(bothinthesameplotandin2di erentsubplots).Makesuretoaddlabelsandalegendandusedi erentlinestylesandcolorsfortheplots.[EndofExercise]23.4PolynomialsApolynomialisexpressedas:p(x)=p1xn+p2xn1+:::+pnx+pn+1(23.17)wherep1;p2;p3;:::arethecoecientsofthepolynomial.WewillusethePolynomialModuleintheNumPyPackage.Web:https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.polynomials.polynomial.htmlOtherResources:PythonAdvancedCourseTopics-Polynomials:https://www.python-course.eu/polynomialclassinpython:php125
Figure23.3:TrigonometricFunctions126
Figure23.4:RightTriangleFigure23.5:LawofCosines127
PartVIResources128
Chapter24PythonResourcesHereyou ndmyWebpagewithPythonresources[1]:https://www.halvorsen.blog/documents/programming/python/PythonHomePage[6]:https://www.python.orgPythonStandardLibrary[18]:https://docs.python.org/3/library/index.html24.1PythonDistributionsAnaconda:https://www.anaconda.com24.2PythonLibrariesNumPyLibrary:http://www.numpy.orgSciPyLibrary:https://www.scipy.orgMatplotlibLibrary:https://matplotlib.org24.3PythonEditorsSpyder:https://www.spyder-ide.org129
VisualstudioCode:https://code.visualstudio.comVisualStudio:https://visualstudio.microsoft.comPyCharm:https://www.jetbrains.com/pycharm/Wing:https://wingware.comJupyterNotebook:http://jupyter.org24.4PythonTutorialsPythonTutorial-w3schools.com[13]:https://www.w3schools.com/python/ThePythonGuru[19]:https://thepythonguru.comWikibooks-ABeginner’sPythonTutorial:https://en.wikibooks.org/wiki/ABeginnerTutorialsPoints-PythonTutorial:https://www.tutorialspoint.com/python/TheHitchhiker’sGuidetoPython:https://docs.python-guide.orgGoogle’sPythonClass:https://developers.google.com/edu/python/24.5PythoninVisualStudioWorkwithPythoninVisualStudiohttps://docs.microsoft.com/visualstudio/python/130
Bibliography[1]H.-P.Halvorsen,\Technologyblog-https://www.halvorsen.blog,”2018.[2]H.-P.Halvorsen,\Technologyblog-https://en.wikipedia.org/wiki/Python(programminglanguage);002018:[3]T..T.P.Languages,\The2018topprogramminglanguages-https://spectrum.ieee.org/at-work/innovation/the-2018-top-programming-languages,”2018.[4]S.Over
ow,\Stackover
owdevelopersurvey2018-https://insights.stackover
ow.com/survey/2018/,”2018.[5]stackover
ow.blog,\Theincrediblegrowthofpython-https://stackover
ow.blog/2017/09/06/incredible-growth-python/,”2018.[6]python.org,\python.org-https://www.python.org,”2018.[7]python.org,\Thepythontutorial-https://docs.python.org/3.7/tutorial/,”2018.[8]python.org,\Python3.7.1documentation-https://docs.python.org/3.7/,”2018.[9]scipy.org,\Scipy-https://www.scipy.org,”2018.[10]matplotlib.org,\Matplotlib-https://matplotlib.org,”2018.[11]pandas,\pandas-http://pandas.pydata.org,”2018.[12]Wingware,\Wingwarepythonide-https://wingware.com,”2018.[13]w3schools.com,\Pythontutorial-https://www.w3schools.com/python/,”2018.[14]Wikipedia,\Debugging-https://en.wikipedia.org/wiki/Debugging,”2018.[15]TechBeamers,\Getthebestpythonide-https://www.techbeamers.com/best-python-ide-python-programming/,”2018.[16]Jupyter,\Jupyter-https://jupyter.org,”2018.[17]JupyterHub,\Jupyterhub-http://jupyter.org/hub,”2018.131
[18]python.org,\Thepythonstandardlibrary-https://docs.python.org/3/library/,”2018.[19]T.P.Guru,\Thepythonguru-https://thepythonguru.com,”2018.132
PartVIISolutionstoExercises133
StartusingPythonSimulationandPlottingofDynamicSystemGiventheautonomoussystem:_x=ax(1)Where:a=1TwhereTisthetimeconstant.Thesolutionforthedi erentialequationis:x(t)=eatx0(2)SetT=5andtheinitialconditionx(0)=1.CreateaScriptinPython(.py le)whereyouplotthesolutionx(t)inthetimeinterval:0t25AddGrid,andproperTitleandAxisLabelstotheplot.PythonScript:1importmathasmt2importnumpyasnp3importmatplotlib.pyplotasplt456#ModelParameters7T=58a=1/T910#SimulationParameters11x0=112t=01314tstart=0134
15tstop=251617increment=11819x=[]20x=np.zeros(tstop+1)2122t=np.arange(tstart,tstop+1,increment)232425#DefinetheFunction26forkinrange(tstop):27x[k]=mt.exp(at[k])x0282930#PlottheSimulationResults31plt.plot(t,x)32plt.title(‘SimulationofDynamicSystem’)33plt.xlabel(‘t’)34plt.ylabel(‘x’)35plt.grid()36plt.axis([0,25,0,1])37plt.show()ThesimulationgivestheresultsasshowninFigure1.Figure1:SimulationofDynamicSystem[EndofExercise]135
PythonProgrammingc
Hans-PetterHalvorsenAugust12,2020ISBN:978-82-691106-4-7136

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *