ebook img

Learn Python 3 PDF

149 Pages·2022·2.649 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Learn Python 3

Contents Introduction 1 IntroductiontoProgrammingLanguages . . . . . . . . . . . . . . . . . . . . . . . . . . 1 IntroductiontoPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 AdvantagesofPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 InstallingPythoninWindows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 InstallingPythoninmacOS(Apple) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 ExecutionModes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 InteractiveModeofExecution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 ScriptModeofExecution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 PythonFundamentals 11 Tokens: Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Tokens: Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Tokens: Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Tokens: Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Tokens: Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Tokens: Delimiters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 CharacterSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 BlocksandIndentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Variables,Objects&DataTypes 21 WhatareObjects&Variables? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Variables&AssignmentStatements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Built-inDataTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 TypeChecking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 TypeCasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Mutable&ImmutableDataTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Input/Output 31 HowtoAcceptUserInput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 DisplayingOutput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 Operators&Expressions 35 IntroductiontoOperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 ArithmeticOperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 RelationalOperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 AssignmentOperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 LogicalOperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 IdentityOperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 MembershipOperators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 OperatorPrecedencewithExamples . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Errors&ExceptionHandling 49 ErrorTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 i 㶻 㰐 github.com/animator/learn-python· edpunk.com AnkitMahato SyntaxError . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 RuntimeError . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 LogicalError . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 ExceptionHandling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 ControlFlow 57 IntroductiontoControlFlow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 SequentialFlow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 SelectionStatements: if.. else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Iteration: for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Iteration: while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 JumpStatements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 NestedLoops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 Strings 71 Strings: Introduction&Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 AccessingCharactersofaString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 StringOperations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 IntroductiontoStringMethods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 ConvertCaseofStrings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 CheckCharactersofaString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 SplitaString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 StripCharactersfromaString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 CheckPrefixorSuffixinaString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 Find&ReplaceCharactersinaString . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 TraversingaString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 List 83 WhatisaPythonList? HowtoCreateaList? . . . . . . . . . . . . . . . . . . . . . . . . 83 AccessingItemsofaList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 ModifyingaList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 RemovingItemfromaList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 ListOperations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 TraversingaList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Built-inFunctionsthatcanbeusedforaList . . . . . . . . . . . . . . . . . . . . . . . . 88 IntroductiontoListMethods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 AddingItemstoaList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 RemovingItemsfromaList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 CountingorLocatingItemsinaList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 ReversingItems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 SortingaList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 CopyingaList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 NestedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 ListComprehension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 SamplePrograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Tuple 97 ListvsTuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 HowtoCreateTuple? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 WhatisaSingleton? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 AccessingItemsofaTuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 TuplesareImmutable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 TupleOperations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 TraversingaTuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Built-inFunctionsthatcanbeusedforaTuple . . . . . . . . . . . . . . . . . . . . . . . 101 LocatingItemsinaTuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 CountingtheOccurrenceofanItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 NewTuplewithReversedItems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 ii 㶻 㰐 github.com/animator/learn-python· edpunk.com AnkitMahato NewTuplewithSortedItems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 NestedTuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 UnderstandingtheImmutableNatureofTuples . . . . . . . . . . . . . . . . . . . . . . . 103 Dictionary 105 WhatisaDictionary? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 HowtoCreateaDictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 AccessingItems(Key:Value)ofaDictionary . . . . . . . . . . . . . . . . . . . . . . . . . 106 UpdatingaDictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 RemovinganItem(Key:Value)fromaDictionary . . . . . . . . . . . . . . . . . . . . . . . 108 DictionaryOperations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 TraversingaDictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 Built-inFunctionsforaDictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 CreatingaCopyofaDictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 NestedDictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 SamplePrograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 PythonStandardLibrary 115 Built-inFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 MathematicalFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 TypeFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 I/OFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Base/UnicodeConversionFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 WhatareBuilt-inModules? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 mathModule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 randomModule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 statisticsModule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 FileHandling 123 FileHandlinginPython-Introduction&Overview . . . . . . . . . . . . . . . . . . . . . . 123 TextFilesvsBinaryFiles-UseCase,FileFormats,Examples . . . . . . . . . . . . . . . . 123 FileOpening&Closing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 FileReading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 WritingaFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 Reading&WritingBinaryFilesusing pickle Module . . . . . . . . . . . . . . . . . . 129 Reading&WritingaCSVFileusing csv Module . . . . . . . . . . . . . . . . . . . . . 131 UserDefinedFunctions,Modules&Packages 135 UserDefinedFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 FunctionStructure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 ParametersandArguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 ScopeofVariables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 PassingObjectsofMutableTypetoaFunction . . . . . . . . . . . . . . . . . . . . . . . 139 WhatisaModule? HowtoCreateaModule? . . . . . . . . . . . . . . . . . . . . . . . . 140 ExecutableScripts/Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 WhatisaPackage? IntroductiontoPyPi. HowtoCreateaPythonPackage? . . . . . . . . 142 iii 㶻 㰐 github.com/animator/learn-python· edpunk.com AnkitMahato iv Introduction Introduction to Programming Languages Intoday’sdigitalera,wedependoncomputers,smartphonesandtheinternettoperformaplethoraof tasks,like: • Amathematicaltask,suchasfindingthesquarerootofanumberorsolvingasetofsimultaneous equations. • Atext-basedtasksuchasreadingadocumentandperformingsearch/replace. • Streamingandplayingmultimediafilescontainingaudioandvideo. • Usingasearchenginetofindandvisitawebsite. • Playinganonlinemultiplayergamewithfriends. • andmanymore… Softwaresplayanimportantroleastheytranslatehumanactivityintocorrespondingmachineinstructions whichareexecutedtoaccomplishthesetasks. A software is a collection of programs where each program provides a sequence of instructions specifyinghowthecomputershouldact. Theseinstructionshavetobeprovidedinmachinelanguageorlowlevellanguage(0sand1s)thatis difficulttoreadorwriteforahumanbeing. Thisledtotheinventionofhigh-levelprogramminglanguagesinwhichprogramscanbeeasilywritten andmanaged. Thehuman-readableprogramswrittenusinghigh-levellanguagesareconvertedinto computer-readablemachinecodeorbytecodeusingcompilersorinterpreters. Therearemanyhigh-levelprogramminglanguagesthatarecurrentlyinwideuse. Some of the popular languages are Java, C, C++, C#, Go, Swift, JavaScript, PHP, Dart, Kotlin and Python. Introduction to Python GuidovanRossumstartedthedevelopmentofPythoninDecember1989. Hereleasedthefirstversion (0.9.9)ofPythonforgeneralpubliconFebruary20,1991. Thelanguageevolvedoverthenextfewdecadesandsodiditsdefinition,thecurrentversionofwhich isstatedbelow: Python is a high-level, interpreted, object-oriented programming language with dynamic semantics. LetusbreakdownandanalyzetheabovedefinitiontogainabetterunderstandingofPython: High-level Pythonisahigh-levelprogramminglanguagewhichcanbeusedtowriteaprograminnaturallanguage (english)makingitreadable,writable,shareableandmanageable. 1 㶻 㰐 github.com/animator/learn-python· edpunk.com AnkitMahato WhiledevelopingaPythonprogramoneisnotrequiredtohandlethevariouscomponentsofcomputer architecturelikeregisters,memoryaddressesandcallstackswhichhavetobehandledifanassembly languageoralow-levellanguageisusedfordevelopment. Python includes high-level language features like variables, data structures (lists, dictionaries, etc.), objects,expressions,modules,classes,functions,loops,threads,filehandling,stringhandling,error handlingandothercomputerscienceabstractionconcepts. Interpreted IntraditionalprogramminglanguageslikeCorC++,codesarecompiledintocomputer-readablemachine codebeforeitcanbeexecuted. PythonisaninterpretedlanguagewherethePythoninterpreterreadsandexecutestheprogramline byline. Theprocessismoretimeconsumingcomparedtocompiledcodeexecution,butallowsfasterdevelop- mentasonedoesnothavetogothroughtheentirecompilationstepduringtestinganddebugging. Also, the code can run on any platform as long as it has a valid Python installation (which includes interpreter)asthereisnogenerationofplatformdependentbinaries. Object-oriented PythondoesnotenforceObject-orientedprogramming(OOP),butcompletelysupportsit. AprogrammercandefineClassesspecifyingthedataintheformofattributes(orproperties)andsome programminglogicintheformofmemberfunctions(ormethods). Onceaclassisdefined,theusercan createaninstanceofthatclasswhichisknownasanobject. InPython,everything( int , list , dict ,etc.) isanobject. Wewillcovermoreaboutobjectsin detailinthelatersections. DynamicSemantics AsPythonisaninterpretedlanguageinwhichthecodeisexecutedline-by-line,apythonstatementor expressionisevaluatedduringrun-time. Thisallowsdynamictyping(typeofavariablecanchangeover itslifetime)andcreationofdynamicobjectsduringrun-time,whichprovidesmoreflexibility,usability andfewerlinesofcodeascomparedtostatically-typedcompiledlanguageslikeC/C++. Advantages of Python ThekeyadvantagesofPythonareasfollows: 1. EasytoLearn ThePythonprogramminglanguageiseasytolearnwithlowtechnicalandconceptualoverhead. This makesitanideallanguageforbeginnerstolearnprogramming. 2. ClearSyntax&FewerLinesofCode Python’ssimpleandeasytolearnsyntaxincreasescodereadabilityandleadstofewerlinesofcode. AtypicaltaskwhichrequiresanaverageoftwentylinesofcodeinCandseveninJavacanoftenbe donewithjustonelineinPython. Also,duetofewerlinesofcodethechancesofmakinganyerrorissignificantlyreduced. 3. OpenSource Python is an open source programming language, so anyone can view and contribute to its source code. 4. Portable&PlatformIndependent The Python programming language is portable & platform independent as it can work on any Linux, MacOSorWindowsdevice. 5. StandardLibrary&PythonPackages 2 㶻 㰐 github.com/animator/learn-python· edpunk.com AnkitMahato PythonhasarichandextensiveStandardLibrary,acollectionofpredefinedfunctionsforvarioustasks. Python programmers also have at their disposal the vast ecosystem of more than 250,000 commu- nitycontributedlibrariesinthePythonPackageIndex(PyPI),whereonecanfindasolutiontoevery conceivabletask. 6. WebApplicationDevelopment Someofthemostpopularwebdevelopmentframeworks(django,flask,etc.) arewritteninPython. This coupledwiththeavailablityofpackagestoconnecttoanydatabasemakesPythonagreatchoicefor webapplicationdevelopment. Installing Python in Windows Let’sstartwiththePython3installationprocessonWindowsoperatingsystem. Step1: DownloadInstaller DownloadthelatestWindowsinstallerfromthePythonSoftwareFoundationwebsite. Step1: DownloadInstaller Step2: InstallPython3 Oncethedownloadiscompletedouble-clickandrunit. 3 㶻 㰐 github.com/animator/learn-python· edpunk.com AnkitMahato Step2: InstallPython3 ✅ Selectthecheckbox Add Python 3.9 to PATH . Thiswillenableyoutoinstallpythonpackages andrunpythonscriptviacommand-line.  Hit Install Now andcompletethesetup. Step3: VerifyInstallation Oncethesetupiscomplete,clickonthe Start menuandopen Python 3.9 -> IDLE (Python 3.9 64 bit) tolaunchthePythoninterpreter. Step3: LaunchPythonInterpreter Python3.9isnowsuccessfullyinstalledonyourcomputer. 4 㶻 㰐 github.com/animator/learn-python· edpunk.com AnkitMahato Step3: VerifyInstallation Installing Python in macOS (Apple) Let’sstartwiththePython3installationprocessonmacOSoperatingsystem. Step1: DownloadInstaller DownloadthelatestmacOSinstallerfromthePythonSoftwareFoundationwebsite. Step1: DownloadInstaller Step2: InstallPython3 Oncethedownloadiscompletedouble-clickandrunit. 5

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.