Python Bookcamp: Exercises And Projects - Anarcho-Copy

Transcription

Python BookcampExercises and Hands-on ProjectsVaskaran Sarcar

Python Bookcamp: Exercises and Hands-on ProjectsCopyright 2021 by Vaskaran SarcarThis work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part ofthe material is concerned, specifically the rights of translation, reprinting, reuse of illustrations,recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission orinformation storage and retrieval, electronic adaptation, computer software, or by similar or dissimilarmethodology now known or hereafter developed.ISBN-13: 979-8581409275ASIN: B08FTD48NFTrademarked names, logos, and images may appear in this book. Rather than use a trademark symbolwith every occurrence of a trademarked name, logo, or image we use the names, logos, and imagesonly in an editorial fashion and to the benefit of the trademark owner, with no intention of infringementof the trademark.The use in this publication of trade names, trademarks, service marks, and similar terms, even if theyare not identified as such, is not to be taken as an expression of opinion as to whether or not they aresubject to proprietary rights.While the advice and information in this book are believed to be true and accurate at the date ofpublication, neither the author nor the editor nor the publisher can accept any legal responsibility forany errors or omissions that may be made. The author and publisher make no warranty, express orimplied, for the material contained herein.For information on translations, please e-mail vaskaran@rediffmail.com.Any source code or other supplementary material referenced by the author in this book is available n@rediffmail.comFor more detailed information, please email

I dedicate this book to all the unsung heroes andvolunteers who are fighting at the front lines of Covid19 battle to save humanity and this beautiful world.

ContentsAbout the AuthorAcknowledgmentsPrefaceChapter 1: Getting Ready for Program ExecutionOverviewSetting Up the Programming EnvironmentUsing Command PromptUsing IDLEUsing PyCharm IDEExecuting Simple ProgramsDemonstration 1OutputDemonstration 2OutputDemonstration 3OutputChapter 2: Comments, Variables, and OperatorsUsing CommentsDemonstration 1OutputAnalysisIntroduction to VariablesStrings vs Numbersint vs floatDemonstration 2OutputAnalysisNaming ConventionsAssigning Multiple Variables in a Single LineAssigning Same Value to Multiple VariablesOperatorsArithmetic OperatorsAssignment OperatorsComparison (or Relational) Operators

Logical OperatorsBitwise OperatorsPrecedence of OperatorsOperators AssociativityIdentity OperatorsMembership OperatorsSolution to ExercisesGeneral Comments for Case StudiesCase Study IChapter 3: Common Data TypesCode Demonstrations with StringsCode Demonstrations with NumbersQuick talk on f-stringsAccepting User InputsDemonstration 1OutputSolution to ExercisesCS 1.1 ImplementationCase Study IIChapter 4: Decision MakingUsing an if StatementDemonstration 1OutputUsing the if-else StatementsDemonstration 2OutputDemonstration 3OutputDemonstration 4OutputUsing elif with an if-else StatementDemonstration 5OutputDemonstration 6OutputAnalysis

Tautology and ContradictionsAlternative DesignsDemonstration 7OutputAnalysisDemonstration 8OutputSolution to ExercisesCS 2.1 ImplementationCase Study IIIChapter 5: Iteration using LoopsThe Purpose of IterationThe while LoopDemonstration 1OutputDemonstration 2OutputAnalysisThe for LoopDemonstration 3OutputAnalysisDemonstration 4OutputAnalysisUse of break StatementDemonstration 5OutputAnalysisUse of continue StatementDemonstration 6OutputAnalysisNested LoopDemonstration 7OutputAnalysisSolution to Exercises

CS 3.1 ImplementationCase Study IVChapter 6: Advanced Data TypesWorking with ListsWorking with TuplesWorking with DictionariesWorking with SetsSolution to ExercisesCS 4.1 ImplementationPossible improvementsCase Study VChapter 7: Functions and ModulesFunction OverviewDemonstration 1OutputAnalysisArgument vs ParameterDiscussion on Function ArgumentsPositional ArgumentKeyword ArgumentsUse of Default ValuesDemonstration 2OutputDemonstration 3OutputAnalysisDiscussion on Return ValuesDemonstration 4OutputDemonstration 5OutputLambda FunctionDemonstration 6OutputDemonstration 7Output

ModulesDemonstration 8OutputUsing AliasDemonstration 9OutputDemonstration 10OutputQuick Discussion on pipSolution to ExercisesCS 5.1 ImplementationPossible ImprovementsCS 5.2 ImplementationPossible ImprovementsCase Study VIChapter 8: Exception ManagementTypes of MistakesGeneral PhilosophyCommon termsPython ExceptionsDemonstration 1Case Study with Valid InputsCase Study with an Invalid InputCase Study with another Invalid InputKey Points of the Exception-handling MechanismDemonstration 2Case Study with Valid InputsCase Study with an Invalid InputCase Study with another Invalid InputDemonstration 3Case Study with Valid InputsCase Study with Invalid InputsUse of pass StatementDemonstration 4Case Study with Valid InputsCase Study with an Invalid InputAnalysis

Arranging Multiple except BlocksCase Study with an Invalid InputCase Study with another Invalid InputCustom ExceptionDemonstration 5OutputDebugging Code Using assert StatementDemonstration 6OutputDemonstration 7OutputAnalysisSolution to ExercisesCS 6.1 ImplementationCase Study VIIChapter 9: Programming with FilesReading from a FileQuick Talk about File PathsDemonstration 1OutputAnalysisWriting to a FileDemonstration 2OutputAnalysisAlternative Way to Read and WriteDemonstration 3OutputAnalysisWorking with Binary FilesDemonstration 4OutputRenaming and Removing FilesDemonstration 5OutputUsing with KeywordDemonstration 6Output for Approach1

Output for Approach2Output for Approach3Handling FileNotFoundErrorDemonstration 7OutputAnalysisSolution to ExercisesCS 7.1 ImplementationChapter 10: Object-Oriented Programming ConceptsClass and hismQ&A SessionCase Study VIIIChapter 11: Class, Objects, and InheritanceConstructing the Building Blocks for OOPDemonstration 1OutputAnalysisConstructorDemonstration 2OutputAnalysisLooking into Instance Creation ProcessDemonstration 3OutputAnalysisChanging an Attribute ValueDemonstration 4OutputWorking with Default AttributesDemonstration 5

OutputAnalysisImporting ClassesDemonstration 6OutputAnalysisDemonstration 7OutputDemonstration 8Demonstration 9OutputUse of Identity OperatorDemonstration 10OutputInheritanceDemonstration 11OutputAnalysisUpdated ImplementationOutputDemonstration 12OutputPrivate Variables and MethodsDemonstration 13OutputAnalysisStatic Methods and Class MethodsUnderstanding the DifferenceDemonstration 14OutputAnalysisSolution to ExercisesCS 8.1 ImplementationPossible improvementsChapter 12: Test Your CodeThe Code for TestingTesting FunctionsDemonstration 1OutputDemonstration 2

OutputAnalysisTesting ClassDemonstration 3OutputSolution to ExercisesIndex

About the AuthorVaskaran Sarcar obtained his Master ofEngineering in Software Engineering from Jadavpur University, Kolkata(India), and an MCA from Vidyasagar University, Midnapore (India). He wasa National Gate Scholar (2007-2009) and has over 12 years of experience inEducation and the IT industry. He devoted his early years (2005-2007) toteach at various engineering colleges, and later he joined HP India PPS R&DHub Bangalore. He worked there until August 2019. At the time of hisretirement from the IT industry, he was a Senior Software Engineer andTeam Lead at HP. To follow his dream and passion, Vaskaran is now anindependent full-time author. Other books by him include:Design Patterns in C# Second Edition (Apress,2020)Getting Started with Advanced C# (Apress,2020)Interactive Object-Oriented Programming in Java Second Edition(Apress,2019)Java Design Patterns Second Edition (Apress,2019)Design Patterns in C# (Apress,2018)Interactive C# (Apress,2017)Interactive Object-Oriented Programming in Java (Apress,2016)Java Design Patterns (Apress,2016)C# Basics: Test Your Skills (Createspace,2015)Operating System: Computer Science Interview Series(Createspace,2014)

AcknowledgmentsAt first, I thank the Almighty. I sincerely believe that with HIS blessingsonly, I could complete this book. I extend my deepest gratitude to all myfamily members, my publisher, the editorial board members, and everyonewho directly or indirectly supported this book.

PrefaceWelcome to your journey through Python Bookcamp: Exercisesand Hand-on Projects. This is an introductory guide to the Pythonprogramming. Before you jump into the topics, I want to highlighta few points about the goal and the organization of the book.The primary goal of this book is to make you familiarwith Python programming as quickly as possible. Onceyou learn the concepts in this book, you’ll be ready toexplore further. I have been involved in teaching since2005. I have taken classes at both engineering and nonengineering colleges. This is the true motivation tointroduce a book like this.The book helps you to learn the fundamental conceptseffectively. What is an effective way? Ok, once you learna topic, if you repeatedly practice and try to write code,you are on the right track. This is why this book hasmultiple exercises and hands-on projects. The bookfollows a steep learning curve, where you keepimplementing these case studies using the concepts youlearn in a previous chapter.Starting from the second chapter, each chapter in thisbook contains exercises too. These exercises are neithertoo easy nor too tough. These are within your optimalzone of difficulty. As per Goldilocks rule, you canmotivate yourself and act better in these situations. Theexercises and case studies help you test yourunderstanding and raise your confidence level.Many of us are afraid of fat books because they do notpromise that we can learn the subject in one day or 7days. But you know that learning is a continuous process.

It is hard to achieve any real mastery in 24 hours or 7days. So, the motto of the book is “To learn the coretopics of Python, whatever effort I need to put, I am okwith that.” Still, simple arithmetic says that if you cancomplete one topic in one day, you can complete the bookwithin 12 days (your learning speed depends only on yourconcentration level, focus, and dedication). But thisarithmetic calculation is secondary! I have designed thebook in such a way that upon completion of the book, youwill know the core concepts in Python. Most importantly,you’ll know how to learn further.Python is a very popular computer language and widelyused. Like other popular programming languages, itgrows continuously to give us support with additionalfeatures and functionalities. When I started writing thisbook, Python3.8 was the latest version. So, everything inthis book should run in Python 3.8 and upcomingversions. I choose this version for another reason. Theofficial website tells us that Python 3.x (Commonlyknown as Python 3) is the future of the language, butPython 2. x (Also known as Python 2) is the legacy. Youmay see some old Python projects with Python2, but Irecommend you to learn and use Python3.Once you are familiar with a good programminglanguage, you find many similarities with otherprogramming languages. As an obvious result, you canmotivate yourself to learn a new programming languageand this time it will be even easier to grasp.How the book is organized?The book has the following organization:

The first chapter is a warm-up session for you. Hereyou’ll set up your programming environment and makeyourself ready for further learning. In the Chapter 2,you’ll learn about comments, variables, and operators.I told you that this book includes multiple exercises andprojects. An implementor must know what he/she isgoing to implement. So, at the beginning of eachsubsequent chapter, you will get an overview anddescription of the project that can be implemented. Onceyou finish reading the chapter, you’ll get the completeimplementation of the projects.In Chapter 3, you’ll learn about common data types,such as strings and numbers in Python. In Chapter 4,you’ll learn about decision making in your program.Chapter 5 talks about iteration. Here you’ll learn aboutloops and the usage of break and continue statements. InChapter 6, you’ll learn advanced data types, such aslists, tuples, sets, and dictionaries. Chapter 7 teaches youhow to use functions to make your code more Pythonic.You’ll also learn about modules and their usage. Chapter8 talks about exceptions and how to manage them.Chapter 9 teaches you file handling mechanisms.Chapter 10 and Chapter 11 of this book briefly cover theobject-oriented programming basics and show you theusage of classes, objects, and inheritances. Here you alsolearn about static methods, class methods, and privatevariables, etc. At the end of the book, there is a chapter(Chapter 12) to show how to write useful tests to verifyyour code.You can download all the source codes of the book fromGitHub (I already gave you the online link). I have aplan to maintain the “Errata” and if required, I can alsomake some announcements there. So, I suggest that youvisit those pages to receive any important corrections orupdates.

Prerequisite KnowledgeThe target readers for this book are those who are new to Pythonprogramming. The book will be super easy for the readers with theleast coding experience in any other high-level computer language.I assume that you can download a software installer following theonline instructions and you already installed Python on yourcomputer. So, I do not spend time on this topic. It is because youcan find them easily both online and offline.Who is this book for?In short, you can pick the book if the answer is “yes” to the followingquestions:Have you never programmed before, but eager to learnPython?Do you have experience with one or more high-levelprogramming languages, but want to learn Python thistime?Do you want to explore the Python basics step-by-step,but as quickly as possible?Do you want to be familiar with object-orientedconcepts like polymorphism, inheritance, abstraction,and encapsulation?Do you know how to install software on a machine andthen set up the coding environment?Do you like to review your knowledge before you usePython in advanced fields such as data science, machinelearning?Probably you shouldn’t read this book if the answer is yes to anyof the following questions:Are you confident about the fundamentals of Python?

Are you looking for advanced concepts in Python,excluding the topics mentioned previously?Do you dislike a book that has an emphasis onexercises?“I dislike Windows OS, and PyCharm. I want to learnand use Python without them only.”-Is this statementtrue for you?Guidelines for Using This BookHere are some suggestions so you can use the book moreeffectively:I suggest you reading these chapters sequentially. Thereason is that some fundamental techniques/conceptsmay be discussed in a previous chapter, and I do notrepeat the same in a subsequent chapter.I also suggest that you complete the exercises in achapter before you enter a new chapter. This process cangive you confidence, which can give you a better pay-offsoon.Indentation is an important part of Python programming.We consider anything indented as a block of code inPython. Based on your device’s screen size, you may notsee the correct indentation in some programs. I suggestthat you refer to the actual code in those cases. You candownload the actual code from the online linkhttps://github.com/Vaskaran/PythonBookcamp. Imentioned this link at the beginning of this book.It is worth mentioning that I could use IDLE, which isPython’s Integrated Development and LearningEnvironment. It provides some basic functionalities suchas syntax highlighting, different uses of colors for betterreadability. But I have used Python Command Shell (for

the initial chapters where lines of code are very short)and PyCharm Community Edition 2020.1.1 in theWindows 10 environment. PyCharm has manyinteresting features and when you work with largeprojects, those features are very useful. The Communityedition of PyCharm is also free of cost. If you do not usethe Windows operating system, you can also use VisualStudio Code, which is also a source-code editordeveloped by Microsoft to support Windows, Linux, orMac operating systems. This multi-platform IDE is alsofree.In some cases, I have shortened the long URLs for abetter presentation. For example, you’ll seehttp://bit.ly/python-exceptions instead l#: :text In%20Python,%20In this book, I have written the programs are written andexplained the concepts in a way that these differentprogramming environments should not cause any majorproblem to your learning process.I have used Python 3.8 for this book, which was thelatest version available at this time of writing. You cansurely predict that version updates will comecontinuously, but I strongly believe that these versiondetails should not matter much to you because I haveused the fundamental constructs of Python. So, thesecodes should execute smoothly in the upcoming versionsof Python/PyCharm as well. I also believe that theresults should not vary in other environments, but youknow the nature of a software-it is naughty. So, if youlike to see the same output, it is better to mimic the sameenvironment.Remember that you have just started on this journey. Asyou learn about these concepts, try to write your code. Ithelps you write better programs.

Conventions in This BookHere I mention only two points: In many places, to avoid lesstyping, I have used the word “his” only. Please treat it as “his” or“her” -which applies to you.Second, all the outputs and codes of the book follow thesame font and structure. To draw your attention, in some places, Ihave made them bold. For example, consider the following codefragment (I’ve taken it from Chapter 8) and the lines in bold.# Previous codes are skippedexcept ZeroDivisionError as e:print("Invalid input! Your divisor becomes zero!")print(f"Error details:{e}")except ValueError as e:print("Invalid input! Provide a correct input next time!")print(f"Error details:{e}")else:print(f"Result of the division is : {result}")print("The program completes successfully.")Finally, I hope that this book can provide help to you and you willvalue the effort.

Chapter 1: Getting Ready for ProgramExecutionThis chapter briefly talks about the Python language and its importance. Hereyou’ll learn how to set up your programming environment before you executethe programs.OverviewPython is a computer programming language that is rapidly growingnowadays. The primary reasons for its popularity are simplicity andreadability. Guido van Rossum created this in the late 1980s.You can use Python for various purposes. For example, you maynotice its usage in game programming, business applications, toolsdevelopment, etc. Using Python programs, you can automate boring andlengthy tasks to save your time and energy. In recent years, you notice it inemerging fields like data science and machine learning too. Last but not leastis that the Python community is very strong and supportive and they help yougrow faster.Setting Up the Programming EnvironmentPython is a high-level language. So, you can avoid direct interaction withregisters, memory addresses, call stacks, etc. Instead, you write your programin plain English. So, how the computer will understand the instructions?Well, you may need to be familiar with two terms-compilers and interpreters.I’ll cover them later. Now you can keep in mind the simple distinctionbetween these two: An interpreter translates one instruction (or statement) ata time into machine code. But a compiler takes the entire program and thentranslates it into machine language in one shot. For now, you remember thatyou need a Python interpreter to interpret these programs. So, you need to getthe interpreter and install it before you write your programs. You need to pick

the correct interpreter based on your operating system.A popular programming language grows continuously to give ussupport for more features and functionalities. When I started writing thebook, Python3.8 was the latest version. So, everything in this book shouldrun in Python 3.8 and upcoming versions. I choose this version for anotherreason. The official website tells us that Python3.x (known as Python 3) is thefuture of the language, but Python2.x (known as Python 2) is the legacy. So,you may see some old Python projects with Python2, but I recommend you tolearn and use Python3.Using Command PromptYou can use a text editor to write a Python program. For example, you canuse a notepad. But before you do this, let us begin with a simple commandprompt to check whether Python is installed in your system. So, open thecommand prompt and type python (See Figure 1-1):Figure 1-1: Checking whether Python is installed in the system.I told you earlier that I assume Python is already installed on yourcomputer. If Python is installed on your computer, you notice the detailedinformation as shown in Figure 1-1. Now you can use some simplecommands for further verification purposes. Each time you enter a commandand press the Enter (or Return) key, the statement will be tested. Here aresome examples:C:\Users\Vaskaran Sarcar pythonPython 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.

2 35 5 3True 2 1False print("Hi")Hi You can type exit() (Or, or Ctrl-Z plus Return ) to quit from thisshell.Using IDLEYou can also launch IDLE to get a python shell where you can executepython commands. For example, to get IDLE in Windows10, you can typeIDLE in the search box as shown in Figure 1-2:What is a shell? In simple terms, it is an environment that is usedto run other programs. We can use shells for both the commandline interface and graphical user interface (GUI). But normallywe use it to refer to the command-line interface of the operatingsystem (OS). Developers often call the terms-‘shell’ and‘terminals’ in the same context interchangeably.

Figure 1-2: Searching IDLEOnce you can see the app, click on it to launch. Now you can see theshell.Figure 1-3: Python 3.8.3 is launched.

This shell waits to get a particular command from the user, executesthe command, and then displays the result. Once this cycle is completed, itwaits for the next command to receive from the user. Let us try this.Type print("Hello World!") after in the shell, and press theEnter key. You can immediately see the output Hello world in the next lineas shown in the following figure.Figure 1-4: Printing ‘Hello World’ using IDLE.Now type 1 2 in the shell and press enter to get the following output: 1 23Now you may try a few more lines of code, and verify the output likethe following: 10 7True 2 7 5FalseHopefully, you get an idea- how to write some simple programs in aPython shell. To execute some basic commands, or to check whether you areready for python programming, this process is fine. But the problem is: onceyou exit from the shell, we lose all these commands. This is why we can usea text file to write a Python program and save the file with the .py extension.In short, the file with the .py extension is called a python script.Using PyCharm IDEI have shown you the use of simple command prompts to make you aware ofthe alternative ways to run your Python programs. But ask any professional

about how they write programs. You’ll come to know that they usespecialized text editors or IDE’s (IDE stands for Integrated DevelopmentEnvironment) to write the code. It is because the use of command prompts isnot suitable for big programs. IDE’s help you highlight the syntax error andthey can provide you automatic suggestions to write error-free code. Theyalso support auto-completion for certain functions and phrases, which areextremely helpful. There are many IDE’s with cross-platform support too.But in the end, a few of them became popular, and widely used for aparticular computer language. For example, Java developers often use Eclipsewhen they write programs; similarly, Visual Studio is very common for .NETdevelopers. The same concept applies here. For Python programming, thereare many IDE’s, and PyCharm is very common. I have used this IDE todevelop my programs (aka python scripts) for this book.Spyder is another open-source and cross-platform IDE, which weoften in Python programming. For my machine learning projects,I use Jupyter Notebook in which you can test Python scripts too.If you install Anaconda distribution on your computer, you canfind both Spyder IDE, Jupyter Notebook, and many other things.But I believe that to learn and test simple Python scripts,PyCharm is a pleasant choice for you. It helps you to organizeyour files, identify syntax errors. You can also set breakpoints topause at specified lines in your program. You find coderefactoring very easy when you use PyCharm.For the following program, I took some screenshots from thePyCharm IDE. These can help you visualize the execution environment. Butnext time onwards, I’ll show you the programs and corresponding outputonly. As said before, to execute the python scripts, PyCharm is NOTmandatory. You can run these programs in various ways (for example usingIDLE, Spyder IDE, Jupyter Notebook, etc). So, it makes little sense to takescreenshots from PyCharm for each of these programs.Let us follow these steps:Step-1: Open PyCharmStep-2: Click on File New Project

Figure 1-5: Creating a project in PyCharm.If you have multiple Python versions installed on your computer,you can see them in the drop-down list in the previous screenshot(Figure 1-5) and you can pick your preferred python versionfrom here. I am using the latest version (3.8) which is availableat the time of this writing.Since I have already executed some python scripts using PyCharm, Iget this option. But for the first time users, you do not see this window.Figure 1-6: Project open options in PyCharm.Step-2.1: I opt for a new Window.

Now I get the following screen. See Figure 1-7.Figure 1-7: The project is opened in a new window.Step-3: Right-click on the project folder name (PythonCrashCourse).Select “New” and then choose “Python File” ( See Figure 1-8)Figure 1-8: Adding a new Python file.Step-3.1: Name it as hello world. See Figure 1-9.

Figure 1-9:Name the file as hello world.pyStep-3.2: Press Enter. Notice that a new python file is created foryou. See Figure 1-10.Figure 1-10: The hello world.py is ready. You can write the codehere.Now you are ready to write your first program in PyCharm.Executing Simple Programs

Now I show you some simple Python programs using PyCharm IDE.Demonstration 1Let us write a simple python program. Type the following line: print("HelloWorld!") in a python file (Refer to the following screen). Now move thecursor to the next line by pressing the “Enter” key as shown in the followingfigure. See Figure 1-11. (I have organized the code of this book chapter-wise.So, in this screenshot, you see other files and directories too.)Figure 1-11: The hello world.py file contains a line of code.Save the file (File Save All (Ctrl S)).Now you can run the program. Right-click on the file name andpress the option Run ‘hello world’ as shown in the following figure. SeeFigure 1-12.

Figure 1-12: Run hello world.py in PyCharmOutputCongratulation! You have successfully executed your first python program inPyCharm IDE. You can see the following output:Hello World!Now I take a snapshot from PyCharm to depict it better. See Figure1-13.

Figure 1-13: The successful execution of the program generates theoutput.If you want to run the program again, you can use the followingbutton as shown in the following figure. Notice that ‘ hello world’ isselected by default before you press the run button. See Figure 1-14.Figure 1-14: Alternative option to run hello world.pyPOINTS TO REMEMBEREvery time you write a new program, you canfollow the same approach. Next time onwards, I’llshow you the programs and output only. It is

because you can run the python scripts in variousways(for example, you can use a Python shell, youmay opt for IDLE, etc). So, it makes little sense totake screenshots from PyCharm in each case.Following the PEP8 guideline (You can referto the link https://www.python.org/dev/peps/pep0008/), I have named my file name hello world.py.This guideline suggests that you choose alllowercase names for your modules. But you canuse underscore to improve readability. I’ll discussmodules later in Chapter 7. For now, you knowthat a module is a python file with a .py extension.Let us have some fun with python scripting and continue to writeanother simple program. In Demonstration2, I am using asterisks (*) to makea shape which makes a triangle shape.Demonstration 2Create a new python file. Let us call it triangle.py and type the followinglines into rint("*****")Now save the file and run the program.OutputHere is the output.*

********************Let us go through another simple program in which I’m calculatingthe sum of two numbers.Demonstration 3Create a new python file. Let us call it sum.py and type the following linesinto it.print("The sum of 12 and 5.7 are as follows:")print(12 5.7)OutputHere is the output.The sum of 12 and 5.7 are as follows:17.7I know that this chapter was a bit slow, but it is important. Thesebrief discussions will help you understand the theory and do the codeexercises in the upcoming chapters.

Chapter 2: Comments, Variables, andOperatorsIn this chapter, you see some buildi

Python is a very popular computer language and widely used. Like other popular programming languages, it grows continuously to give us support with additional features and functionalities. When I started writing this book, Python3.8 was the latest version. So, everything in this book should run in Python 3.8 and upcoming versions.