Download as pdf
Download as pdf
You are on page 1of 305
COMPUTER SCIENCE with python Textbook for SUMITA ARORA Class XI © Programming & Complitational Thinking © Computer System & Organization @ Data Management je Society, Law and Ethics DHANPAT RA! & Co. COM Pure so SCIENCE THON “ [Textbook XI] Sumita Arora com ANN anion Wwe | DHANPAT RAI & CO. (Pvt) Ltd. EDUCATIONAL B TECHNICAL PUBLISHERS www.worldvideweb.conetare Quality of education depends a lot on the curriculum imparted. Since Computer Science Is a rapidly evolving field, CBSE constituted a committee to look Into existing Computer Science curriculum and recommend a curriculum that is modern, relatively light, teaches timeless concepts like computational thinking, is upto International standards and focuses on problem solving skills than just the syntax. The new syllabus of Computer Science (083) is the outcome of the recommendations by the curriculum review committee. The cbjectives of this new syllabus are laudable — focus on clear understanding of concepts, applications of concepts, problem solving skills, develop computational thinking etc. This book has been written keeping all this in mind. This book adheres to the CBSE curriculumn for Computer Science (083) for Class XI. Based of the syllabus, the book has been divided into four units. Unit 1: Programming and Computational Thinking (PCT-1) Programming and Computational Thinking, unit has been divided in 11 chapters, Chapters 2 to 11. This Unit covers basics of Python, fundamentels, conditional and iterative constructs, strings, lists, tuples, dictionaries, sorting and program debugging techniques. The aim of this unit is to lay foundation of problem solving skills through Python programming language. Unit 2: Computer Systems and Organisation (CSO) Computer Systems and Organisation unit has been divided in four chapters, Chapters 12 to 45. This unit toves basic computer organisation, Boolean tagic, deta representation and insight into program execution. The aim of this unit is to give an idea of how the information is represented, organised and processed Inside a computer Unit 3: Dota Monagement (OM-1) Data Management unit has been divided Into five chapters, Chapters 16 to 20. This unit talks about ‘elotional database concepts, SQL basics, table creation ond manipulation, querying, table joins and > Indexes in SQL. Then this unit talks about NoSQL database and covers basics of a NoSQL database Mongo08. The aim ofthis unit isto provide idea of how data is processed in databases of modern age. Unit 4 : Society, Law and Ethics (SLE-1) Fociety Law and Ethics unit has been divided into two chapters, Chapters 21 to 22. This unit covers Cyber sofety basics and guidelines, guidelines and usage rules for using social networks, threats while Taauine websites and how to prevent/counter these along with how to securely communicate data aim of this unit is to know the challenges In safe and secure use of : etn i of cyber facilities and technologies Apart from the text book, we have also provided a practical book a exercises, Although the text book contains sufficient "ercises, yet the additional practice of exercises given In practi Programming and other concepts even stronger. “Progress in’ that contains additional number of practice questions and cal book will make the foundation of Contents w.worldvideweb.cor 1 q GETTING STARTED WITH PYTHON 1-23 LT Introduction “1.2. Python- Pluses 13. Python- Some Minuses (So Human | Like) 1.4 Working in Python 14.1 Working in Default CPytion Distribution 5 14.2 Working in Anaconda Distribution 9 143° Writing and Compiling Python Program with Command Line fn Linux 15 1.5 Understanding First Program/Script 2 PYTHON FUNDAMENTALS . 21 Introduction BG Python Character Set 23 Tokens 231 Keywords 26 232. Weniifiers (Naraes) 233. Literals / Values 234 Operators 35 235° Punctustors 36 24 Barebonesof'a Python Program 7 25. Variablesand Assignments a 25.1 Creating « Variable 1 25.2 Multiple Asignments $4 253 Variable Definition 16 254 Dyuamic Typing 17 d 26 Simple Inputand Output 26.1 Reading Numbers. 49 262 Oulput Through print Staten 52 RRS 3 DATA BANDUNG 67-120 | 3.1 Introduction ‘ 3.2 DataTypes 321° Numbers 63 322 Strings 71 323 Lists and Tuples 73 324 Dictionary 74 33, Mutable and Immutable Types 33.1 Variable Internals. 78 34 Operators 341 Arithmetic Operators. 81 34.2 Reletionat Operators a5 343 Mentity Operators. 3g ee viii f 3A Logical Operators 91 345 Bitwise Operators 95 34.6 Operator Precedence 97 35 Expressions 35.1 Lealuating Expressions 101 352. Type Casting 105 4 CONDITIONAL AND ITERATIVE STATEMENTS yi 182,42 ‘Introduetion z 42 Types of Statementsin Python 43. Statement Flow Control 44. Program Logic Development Tools 441 Floceharts 125 44.2 Pseudocode 126 443 Decision Trees 127 45 TheifStatements of Python 454 The if Statement 129 452 The if-else Statement 151 453° The if-elif Slatement 136 4544 The nested if Statement 138 4.6 Repetition of Tasks ~a Necessity 4.7 ‘The range() Function 4.8. leration/Looping Statements 48.1 The for Loop 482. The while Loop 150 483° Lixp else Statement 154 484. Jump) Statements — break and continue 155 Layp ese Statement 159 Nested Loops 164 5 STRING MANIPULATION 183 - 209 Introduction Comparison Operators 189 5.4 String Slices DEBUGGING PRI 21-226 6.1 Introduction 62. Whatis Debugging? 63 Errorsand Exceptions 63.1. Errors ina Program 212 632. Exceplions 213 100 wt 322 123 125 129 143 145, 147 183 184 185 ram? 4 Now to Debug a prog 7 G41 Debugging Techniques 215 Debugger Tool . Test Working with Integrated Debugger Tool of Spyder IDE 218 652 Working with Python Detugger ~ pdb 222 List MANIPULATION 7A Introduction 72 Creatingand Accessing Lists 7.21 Creating Lists 228 2 Accessing Lists 230 73. Uist Operations 7.3.1 Joining Lists 235 73.2 Repeating vr Reptict 73 Slicing the Lists 74 Working with Lists 75. ListFunctionsand Methods g Lists 236 8 Tuptes 259-289 8 Introduction 82 Creatingand Accessing Tuples S21 Croaling Tuples 260 822 Accessing Tuples 262 83. Tuple Operations S31 Joining Tuples: 265 832. Shieimg the Tuples. 266 84. Tuple Functions and Methods 9 DICTIONARIES 281-306 91 Introduction 9.2 Dictionary -Key:Value Pairs 921 Creating a Dictionary 922 Accessing Elements of a Dictionary 283 923 Characteristics of «Dictionary 29 93 Working with Dieter, ms 234 Multrte Ways of Crosting Dictionaries 285 932 Adding Elements to Di 933° Updating Existin aries: iclionary 291 '§ Elements in a Dictionary 293 834 Deleting Elements from a Dictionary 292 835 Checking for Existence of aK; 238 £36 Prey Prntorga Dictionary 34 93.7 Counting Fy rent sae Ming Frequency of Elements in a List using Dictionary 295 “Dictionary Functions and Methods Zz = 2 28 235, 239 an 289 260 265 20 281 282 288 r www.worldvideweb. CO R UNDERSTANDING SorTING ad 322101 Introduction 102 Whatis Sorting? 307 103 BubbleSort 104. Insertion Sort 308 308 33 323 - 332 323 324 327 333 - 354 333, 334 342 345 355-384 13-1 Introduction 355 tal Number Systems 356 stom 350 Binary Number Systems 356 359 Decimial-to Hex Conversion 34 13.38 Hex-to-Decimal Conversion 365 133.9 Binary-to-Hex Conrersion 365 133.10 Hex to Binary Conversion 365 134. Representing Unsigned Integers in Binary 367 135. Binary Addition 368 ce aa entation 14 [fppootean Loic 4 Development of Booles” Logic 42 Binary Valued Quantities 143 Logical Operations 143.1 Logical Fumcticr 143.2 Lagi! Operstors 387 1433 Exuluation of Boolean: Expressions Usin Basic Logic Gates TAL Inverter (NOT Gate) 393 144.2 OR Gate ares 1443 AND gate 394 86 anor Conapound Statertent orption Lace 4) ime Other Rules of Boolean Logie Algelna 4 MB T4B.1 DeMorgan’s First Theorem 42 rabTIicorem 4003 425 - 440 393 395 395 402 405 407 e 451 ySQLand sql. 452 168.1 Processing Capabilities 452 1682 Data Definition Lan 459 460 1724 Comments 463 17.3. SQL.Command Syntax 463 Sample Database 464 175. Making Simple Queries 467 1751 Accessing Database 467 1752 The SELECT Command 4 1753 Selecting all Columns ios it Reordering Columns in Query Resi fword DISTINCT) 468 feywond 46) Ehinsinating Redundant Data (wit Setecti Viewing Structure of Table fos to Perform Simple Cal from all the Rarws ~ A fons? 470 fel Fields: 471 hiery Output 474 ss ~ WHERE clause 476 Selecting Relational clause 482 PULATION COMMANDS Bata into Tale 510 je Dat wis UPDATE Comat 322 ata with DELETE Command 513 Command S14 BLE Command 517 20 | Basics oF 527 527 539 S51 552 557 559 22 599-610 21 2 APPENDIX 611 - 624 troduction eats to Computer Secu uter Security Threats Viruses, Adware ant Spyrcare 604 vam, Eavesdropping 605 to print Function MongoDB utput using String format() 58S SBS S86 586 588 5oL 593 593 599 599 603 607 611 618 619 623 11 www: worldvideweb.com Getting Started with Python Tq Vis Cheat? 12 Introduetion 1.2 Python - Pluses 13 Python ~ Some Minuses La Werling in Python 15 Understanding Fist ProgranvScaipt INTRODUCTION The word Pytion = isn't il scary 7 Does it bring the image of big, reptile that we prefer to see either in jungles or z00 ? Well, it's time to change the image. Now on, you'll remember word Python for its playfulness and pleasant productivity. Confused ? Well, Don't be — because, now on you'll get introduced to a new programming language namely ‘Python’, which promises to make you a big programming fan -) Python is based on or influenced with fivo programming languages : Python is an easy-to-learn yet powerful object oriented programming language. Il is a very high level programming, language yet as powerful as many other middle-level not so high-level languages like C, C+, Java ete, In this chapter, we shall introduce you to playful world of Piquant Python [Word *Piquant’ means pleasantly stimulating or exciting to the mind]. So, are we ready ? And... here we go. ? COMPUTER SCIENCE WITH PYTHOY, ; sy to Use OO Language o being in cally op Expressive Language h ever-popular “Interpreted Language 1.2. PYTHON ~ PLUSES Though Python lang age came int competing wil 1990's, yet it is t Henne such as C, CH Java etc. In porulan of 4 Tis Completeness index. Although, it is not perfect for every ype “ Cross-platform Language application, yetithas many strengths that ma ue | ¢ Free and Open Source good choice for many situations. Let’s see what 0 ‘: Variely of Usage / Applications these pluses of Pyllion. ee riented laugnage with very simple syntax rules, 1. Easy to Use programmer-friendly. Python is compactand Itisa very high level very casy to use object o Janguage and thus very-very 2. Expressive Language Python’s expressiveness mes olher languages. Reason being - fewer For example, consider following feo sets of codes : ft In Python : Swap values ane its more capable 1 expressing the code's purpose than many lines of code, simpler SyNtax. 1/7 In C++ : Swap Values inta=2,b=3, trp; 3 tmp a,b=b,a aed; betmp; which one is compact and easier to understand ? Need I say more ? :). This is the simplest example, you'l find many more such examples of Python's expressiveness in the due course "3. Interpreted Longuage Python is an interpreted language, not a coy 7 Python i ¢, not a piled language. This means that the Python” tala interprets and executes the code line by line at a time. Ik makes Python a sy-to-debug language and thus suitable for beginners to advanced users. ‘ 4, Its Completeness When yi ython, i a you instal Python, you get everything you need to do real work. You do not need to thieogh en Y adciionat libraries ; all types of required functionality is available Hiei Sao ial yython standard library}, For example, for diverse functionality ahem rare pags, lanes GUL development, network connections and many more "Bates Included” pilosapig ns Meany. Thus, is also called — Python fois 5. Cross-plotform Language Python can run equally w i Pater er ot sual i Res on variety of platforms — Windows, Linux/UNIX, Macintosh. Seetemputets, smart phones ele! ent tha! amazing ? And that makes Python @ tres er words, Python is a portable language. 1. Ifyou install Python throu; “ igh Anaconda eich vcd las eakces tk “ — oe Distribution it loads most libraries and packages with Python: ent languages such as Java (ython), JMET (IronPython) ete. Choprer I: GETTING STARTED WITH PYTHON, 13 www.worldvideweb.c¢ 6, Free and Open Source Python language is freely available i, wi it free, its source-code (ic, open-source also, Do you knoy thout any cost (from www.python.org), And not only is complete program instructions) is also available, ic, it is ¥, you can modify, improve/extend an open-source software | 7. Voriety of Usoge/Applications Python has evolved into a powerful, comple Python is being used in many diverse fields/applications, seme of which ance © Scripting © Rapid Prototyping © Web Applications © GUI Programs © Game development and useful language over these years. These days © Database Applications © System Administrations PYTHON — SOME MINUSES (SO HUMAN LIKE) [Minuses of Python nnn Although Python is very powerful yet simple language with so many advantages, it is not the Perfect Programming language. There are some areas oe Not Where Python docs not offer much or is not thal capable, Let’s see what these are : Not the Fastust Language Libraries than C, Java, Perl | rong on Type + Not Easily Convertible 1. Not the Fastest Longuage Python is an interpreted language not a fully compiled one, Python is first semi-compiled into an internal byte-code, which is then exerted by a Python interpreter. Fully compiled languages are faster than their interpreted counterparts. So, here Python is litle weaker though it offers faster development times but execution-times are not that fast compared to some compiled languages. 2. Lesser Libraries than C, Java, Perl Python offers library support for almost all computing programs, but its library is still not competent with languages like C, Java, Perl as they have larger collections available. Sometimes in some cases, these languages offer better and multiple solutions than Python, 3. Not Strong on Type-binding Python interpreter is not declare a variable as intege pin-point it. 4. Not Easily Convertible Because of its lack of syntax, Python isan easy language lo program in. But this advantage has a flip-side too : it becomes a disadvantage when it comes to translating a program into another Programming language, This is because most other languages have structured defined syntax. Since most other programming languages have strong-syntay, the translation from Python to another language would require the user to carefully examine the Python code and its structure and then implement the same structure into other programming language's syntax. So, now you are familiar with what all Python offers. As a free and open-source language, its users are growing by leaps and bounds. trong on catchin but later store a string mismatch’ issues. For example, if you alue in it, Python won't complain or COMPUTER SCIENCE y index, Python was 4th most popular programn 2 rit 2013 popularly try reason, it's part of your syllabus, Together er Febt y Ae ey PP and Ct Tat after fava, PHP playful Python is an interprete difference between not a compiled language, i would beg J language and an interpreter and a compiler (as. Since Python cand to know the working following information box) oe 1 retotion vs Compllation 2 aes Interpret This language processor converting and executing it program execution cannot resume wat every time the program is executed as Forerror debugging, interpreter is very much useful are removed, unnecessary usage of memory takes place Compiler HLL program into machine language but the conversion manner is tein, converts a HLL(High Level Language) program into machine languaee , Tine by Hine. If there is any error in any line, it reports it at the same i the error is rectified. Interpreter must always be present in the every time dhe program is un, 1 frst interpreted and hen exe a it reports the error(s) at thesametime.Buteneeng as it has to be present in the memory always. also conver entire HLL program in one go, and reports all the errors of the program along ‘with the lin ‘Afterall the enors ate removed, the program is recompiled, and after that the compiler is not neededinge memory as the object program is available. COMPILATION ‘Aer compiaon, ono he iargel cada ls ¥y. Compiler ts na longer require. ¥se Comper convons tho source coda ecutable code in one go) Tn interpretation, Interpreters required to Interpret and ‘source code as it processes the lino by tine | www.worldvi Chapter 1 : GETTING STARTED witht PYTHON 1.4 WORKING IN PYTHON Before you start working in Python, you need to install Python on your computers, There are multiple Python distributions available today. © Default installation available from www.python.org is called CPython installation and comes with Python interpreter, Python IDLE (Python GUI) and Pip (packnge installer). © There are many other Python distributions available these days. Anaconda Python distribution is one such highly recommended distribution that comes preloaded with many packages and libraries (e.g. NumPy, SciPy, Panda libraries © Many popular IDEs are also available e¢, Spyder IDE, PytCharm IDE ete. Of these, Spyder IDE is already available as a par! of Anaconda Python distribution. To install any of these distributions, PLEASE REFER TO APPENDIX A. We shall learn to work With both these distribution types [but my personal favourite is Anaconda ;)— not the reptile, the Python distribution :)} Once you have Python installed on your compute in Python in following different ways : s, You are ready to work on it, You can work ( in Interactive mode (also called Immediate Mode) (ii) in Script mode 1.4.1, Working in Default C The default distribution, CP’ython, comes with Python interpreter, Python IDLE (GUI based) and Pip (package installer. To work in interactive as well as script mode, you need to open Python IDLE. jon Distribution 1.4.1A Working in Interactive Mode (Python IDLE) Interactive mode of working means you type the command - one command at a time, and the " you typ Python exccutes the given command there and then and output. In interactive mode, ' 8 § P you type the command in front of Python command prompt rrexampile, if you type 245 in front of Python prompt, it will give you result as 7: 45'¢—— romeo epson pie be Role renimed 299245 by Python ay: To work - mode, follow the process given below : ()) Click Start button — All Programs + Python 3.6.x —+ 1D Or Click Start button — all Programs -» Python 3.6.x Python GUD) [see Fig. 1.1(2)] Python (command line) Gyan * DLE Pyphen 263344) Prmeisarsy B Fymen3s Mine te) * Bymen3$ Mode Docs O2-(~ Click here o open IDLE, It eva COMPUTER SCIENCE wiry, Pron re you'll see the Python Prompt Shell [see Fig. 1.1(b)] where y Uhre sy (i) Twill open Py signs ic, >>>). La Python 165 She a =—— = ett 32k ar? 18, 16:07:26) [MSC v.1900 ee 3.6.5 [v3.6 5459c093zbs, Mar 28 201 Python 3.65 (3 io oor ores” ‘or “license[)* for more Information. Type “copyright”, “er > Figure 1.1 (6) Python's interactive interpreter - Python Shell. commands in front ofthis Python prompt and Python immediately give you the result. [sev Fig. 1.1(c)] Reina as et bey Bam a me proc iscsi hr Ni 607) 52RD Hojo orion etna teen te mo brane met typed on prompt >>> and Python immediately tetumed the outpat Figure 1 (c) Interactive commands and their output in Python Shell, For example, to print string, “Hello” on the se Python prompt (>>>) “en you need to type the following in front of 99> print ("HeLIo") 1 And Python interpreter will immed; iately display string Hello below the command. To display, you just need to mention name nian or “xpression (Fig. 1.1(¢] in front of the Prompt. Figure 1.1(¢) shows you some sample co: i mands that we typec Python shell and the output return’, thon interpreaoeea ‘umed by Python interpreter, 1.4.18 Working in Script Mode > Interactive mode docs not save ve the comm, © The output 1S sandwiched between the ands entered by you in the form ofa P command lines [see Fig. 1,1(0)]. (i) Click Start button —+ All Programs — Python 34x —- IDLE. [Fig 12: (i) Click File + New in IDLE Pet (i) In the indow you want to sove in [Fig 12/6)] For instance, COMPUTER SCIENCE WITH PYTHOY, with an extension -py: The Python Programs @ file ¥ ave the name to our pr s we §i Program ag ye th en SAY nce, (io) Click File Save a "2(0)}- For inst has -py extension IFIB- 1 Hellopy: 1g be saved on the disk and the saved file will have -py extension, Now your program woul / Program File ted, you can run it by fol hat you created in previous Step 1 by using . dule / Script ; Step 2 : Run Mode lowing the given instructions + After the programscript file is crea (0 Open the desired programiscript fi IDLE's File + Open command. / IF the program / script file is already open, you An directly move to next instruction, le U (i) Click Run -» Run Module command [Fig, 1300] in the open program / script file's | window. You may also press F5 key. [pany Aerize apse Fie Eat Fer [Kan] Cpbars Window Heo ‘Giek at Run Run Module ‘command 19 run the opened program I script. Figure 1.3 (0) Run—» Run Module command (Script mode) (iif) And it will execute all the commands stored in module / program / script that you had opened and show you the ete lh ac IFig. 130)) you the complete output in a separate Python Shell window. Le Pron 183 thet ‘Brent Hinds Help '9cO9s208, Mar 26 2038, 1607; edits" or eersel} $5} MSC v.1960 32 be (intel en wind for more nt Don wind armation, pens enscAUseEs scat "Se ott produces | Python when you |22\¥ella.ny = “tl ! ‘ppligd Run Module. Figure 1,3. (by of am n min the shi dow, +3 (b) Output of * module-run is shown In the shell window. AS you can see th: t with seri module / prog at with script mod. sandwiching 2), ™ 1 script and can geal oan all commands together in the form er in the ut Ti lines together. (No more command: GETTING STARTED WITH PYTHON Chosier 1 1.4.2 Working in Anaconda Distribution Anaconda distribution comes with many preloaded packages and libraries. You ean work in it in both interactive and script modes. Anaconda distribution provides the following tools that you can use to work in Python. ‘© Jupyter notebook. It is a web based, interactive computing environment. th many useful editing, interactive testing and © Spyder. It is a powerful Python IDE debugging features. Let us lear to work with both, 1.4,2A Working in Jupyler Notebook In order to work in jupyter notebook, you need to first launch it using Anaconda Navigator’ as it h Anaconda distribution. has come preloaded wi 7. Launch Anaconda Navigator k on Launch below jupyler notebook tile. From the Navigator window, COMPUTER SCIENCE WITH PYTHON mputing environment, it will be laun; ook p based computing nvr it wil ched ing isa wel ter notebook is ° * d (sce below) acai str mow show you notebook dashboar vser will HOW § Your web browser ¥ Me gceaiee veel ' O tocaont F551 | ‘ - This Is notebook |= prter dashboard J 4. On the notebook dashboard, click at down-arrow next to New button and select Python 3 to create a notebook for executing Python 3.x code. (see figure above). J. Ina new tab, it will open a new notebook where you can write and min your code. © Ovary = Jupyter CChopter 1 = GETTING STARTED WITH PYTHON Interactive Mode 6. te 7 Python code in interactive mode, type code in code cell and click Run. (see ow) |< jupyter Untitled Torun tha code in current code col, Fis et Ven nat | In J: print(thentor I ‘Wire code in tra ! code eal! Figure 1.7 Script Mode 7. To runa script : (a) Write the code of a Python script ~ a group of Python commands ~ ina code cell. (b) Now click on its name to give it a new name (see below). Click hore to give ame to your python scrip!» Rimeme Nombook Ene aneansestamy WE: eens. peint(*hello wenld") Frint(*E a8 prograceing {n Python") ‘A python script having mutiole Figure 1.8, COMPUTER SCIENCE with, PTH, 5 oH eit. (0) Click on save icon first to $v (@ Click Run to run your script: Figure 1.9 (© You can check in the notebook dashboard, which is open in another tab ; it show you the name of your currently saved script. Cc Or = Jupyter Tho sa al - yaaa pop cee @ notebook, use File > New n Figure 1.10 1.4.28 Working in Spyder IDE Spyder is a powerful interactive development environment for the Python Janguage wih advanced editing, interactive testing, debugging and introspection features, In fact DataCaP Seeunity recommends Spyder IDE as the most preferred choice® out of top 5 Pythot development environments recommended by it. Spyder IDE comes preloaded with Anaconda distribution. It is my personal favourite for working on Python. To launch Spyder IDE : > Anaconda (folder name) > Spyder 6. As per URL: Noe/ we dtu con community ttoi/dat-senee- python de 1: GETTING STARIED Witt PYTHON | Spyder Interface | Once the spyder is loaded, you will eo ess fever Coe OBDims +Gawe ne mcrae nen ER Se eo ccm Here yout oat enc ay oie iy qresung Cte ouch niece enrhe tara, Tres atest, Sor To 3 i Editor pane To croata serpis, work here Python Console ‘To workin interactive mode. type commands) here and it wil give the culpul below the command ne Seah Figure 1.31 Interactive Mode To work in interactive mode in Spyder IDE, type your command(s) in the IPython console pane of spyder window, It will give you the output of the command there itself. See figure above where we typed command : print(“Hello*) in the [Python console pane and it gave us the result below it, We favour ANACONDA PYTHON DISTRIBUTION for these simple reasons : (0 itis free and open source ; {i it comes preloaded with many packages and libraries, (li. it offers jupyter notebook (preferred choice for bloggers) and spyder IDE lke toolkits to write and Python scripts ond code interactively. personally use Anaconda Navigator and work with Spyder IDE mostly and also. on Jupyter notebook sometimes. Script Mode To work in script mode in Spyder IDE, type your script’s commands in the editor pane. © To start a new script file, click File + New File, © To save current script, use command File > Save or File > SaveAs. © Python scripts have File extension as .py. COMPUTER SCIENCE WITH PYTHON. we OO Fe arecmoan? One Figure 1.12 © Please make sure to select file type as Python Files, ‘After you have typed your script (and saved it), you can run your script by: © Clicking at Run icon (see below) on the toolbar Or by clicking at Run Run command Or by pressing shortcut he WO EK £0 € 2 Kmneeeo! te yu cn ot hla o any ec by pressing ctrlelin | fond wane catheEson | er the Conse si ae ae wR Beep tan ne of iets tor vee) an enhanced Interactive Pythons rython 6.2.4 Bn (211 pent (hed de" Sag Int oien CChopter | = GETTING STARTED WITH PYTHON : PyScripler IDE — another Popular IDE “There is another free and open source IDE by the name PySeripter IDE available, You can also tse it for writing and executing Python programs if you want. Its interface looks like as shown below. For interactive mode, you can type commands directly In console window and for script ode, you ean write script in the editor pane and then run it by pressing Run icon or through Run menu. Now that you are familiar with different ways of working in Python, we can proceed with our discussion of Python. Although you can work on any of these, my personal favourite is ‘Anaconda Distribution and Spyder IDE with Command Line in Linux 1.4.3. Writing and Compiling Pylhon Progrom To create and run a Python program on Linux platform, you need to do this : (i) Write your program code in a text editor. (i) Save your program with .py extension. (ii) Compile and run on the command prompt by giving appropriate command. Let us see how. Typing Python program in o Text Editor There is a variety of choices for text editors when it comes to Linux. There are command line editors like nano, vim, emacs ete?. ; Or you can work with the GUI editors like Sublime Text, atom, brackets etc, This really is the choice of the user. But here, we will be working with Sublime Text 3. Let us see, how we can write a simple Hello World program in Sublime Text and compile and runitusing the terminal. (Please note that Sublime Text editor must be installed on the machine before you can use it). 7. Vim and emacs have their GUI version as well. * COMPUTER SCIENCE win ime Tea tovindows Key) and search for Sy Ore text Click on the icon and it wil gp Tile -» New or press Ctrl +N on the Coding in Tex! Editor {subli () Open sublime Te | You will find an option (i) Create New File. a (i) Anew untitled file w ill ©] print(’ s the st xt, Pres: in to open SU use command pen. Write the hello world code : folio word") rae) perc menos sre ee Atay GS wan Fo iess RE Pan Peers EIR ey 15 (iv) Save the file with proper extension. For this, use command File — Save or press Ctrl + § from the keyboard. 4 c In the Savv dialog that appears, write the name of the file and give an extension .py. We have named the file as hello.py. Compiling and Running the Code using the Terminal () Open the terminal. ° ne » the terminal. Press Cirl+ Alt+T from the keyboard. A command prompt "i (i) Go the folder where you saved the file’. (ii) Type the following command in fa ‘ont of the Python ¢Filenane>.py "tof the prompt and press enter Thal is we should type followi: Pythonhellopy emmmand lo compile and run our program pellopy 9%. Thereis no concept of of extensions in in, - the syntax accordingly. You can eatery ae line text uses these tens the fe e syntax, -xtensions to identify the form format as well. But we ae not covering that. Chopter 1 : GETTING STARTED WITH PYTHON Pere ee eng Peer eee ey Prereter cere det Pretec amc (ie) will compile and run your program. You will see the output of the program in the terminal window. PrEnere er roy kere caves Preteen ere tery) Preemie ivcrny miter sat coat ioe pera) Prete oe 1.5 UNDERSTANDING FIRST PROGRAM/SCRIPT Let us create our first program —a simple “Hello World” program. (We are using Spyder IDE for this, You can use any of the above mentioned options.) To create this, 1. Start Spyder IDE or any other editor of your choice. 2. 2. Start new file ( fly First Progran print ("Hello World!") ile + New File) and type the following text in the editor window : D Spyder Python Fie) Ese Search Seurce Fur Oe D New fie cee |e bet gon oe ben bee wo Tek ier 5 SO :koO > Bae © mn +o BS Plat resourses ox ne Open. Cte o a 9 one @ xaos») Oe Openinstcleres Cutest || “ _ Here you can get Grint ) help of any object cetrees Tiedaeae [Trcaew | me} | Pytorere I ewe = Python 3.6.8 [Anacon (default, Jan 16 2018, v.1900 32 bit (Intel)} Type “copyright”, “credits “License” for ore inforas IPython 6.2.1 -- An enhanc Interactive Python. In (3): Drrnense | RSET Furivions RW Cnd-ceiner CRLF toeodng UTP COMPUTER SCIENCE wi, oh 3. Now save your script with a desired name, 4 Make sure to select Save as type as Python iad : @ Give .py extension to your python program file. Now run your script by clicking Run icon [ D> ) or by clicking Run 5 R, UN cOmman by pressing FS. (Firstly, click in IPython console window) rr insert Saeee Te lat fun Saoge Bm Boog aber Bec Tech ew kb OSS: 80 -RRSE Hc esee-Btyrennontet sy 2 te [carver | Here you ean get [ieaiieesve | Feedse | hee) | Pyreniouse | Hein eg bnceang UThe Pemetent RW Indctinee cay 8 Cehewe t Memon 148% Analysing Script ond Output Now carefully look at the seri pt that you typed, You typed two lines : # Hy First Program Print ("Hello Woria*) But Python gave you just one line's output as : Hello World} The reason being that an line that begins vw i for the programmer's informa ot °S!RS With a z Symbol is a comment in Python. That witha 2, mon only Python wi completely ignore ali the lines Chopter 1: GETTING STARTED WITH PYTHON Understanding print( ) To print or display output, Python 3.x provides print() function"®. You can use Print() as Print(...) eg» when you wrote a String Hetlo Work is the print ) . . cect 1 be print ] Satementy — PPUnt (“Hello Worldi") ct bee it printed : Hello World! Similarly, to print other strings you may give something like, — String object “My name is Misha” patie print('My name is Misha") to by printed. it will print My name is Misha Carefully look at both the print() statements given above. Could you notice anything other than two different string values ? No ? Carefully notice that the first string is enclosed in double quotes and the second string is enclosed in single quotes. a i print(*HelloWorld!”) joven deubte quotes ae Siri erste i singe gusts print( "My name is Misha") Both these strings are valid in Python. You can enclose your strings in either double quotes or in single quotes, but just ensure that opening and closing, quotation mark should be of same type. You cannot have a string like wing Quotations “Hey there” Following are some valid print( ) statements. print( ‘The Golden Ratio’) print(“has same letters as") print( ‘The God Relation’) With this we have come to the end of this chapter. Let us quickly revise what we have learnt so far. 20. In Python 2.x, print isa statement, not a function. COMPUTER SCIENCE Wp, 2 Progress I fy . ? pytHon Interactive MOD! : Ms a tor and then Spysler IDE or any other IDE of your choice) anata Navigator Start Python (Anacon i ‘ion On the [Python console perform this sesst - Python prompt 35 caleulator ae =e eines 1. In front of Python prompt, meee + oe pe filling mere cee ee ie, Inf 13, ty ' ressions one by ove, Ey pasing return key after every expression, ¢ Inf2] :6*3 It will show output lines starting with Outf 12, ¢9. out(2} : 18 She ei Science with Python and fill it there in PriP 1.1 under Chapter 1 after A. Please check the practical component-book — Progress in Computer 4 ¢ proctically doing it on the computer. portcce WORKING IN SCRIPT MODE ~ iP Progress In Python 12 Start Anaconda Navigator and then Sp iyder IDE or any other IDE of your choice. Open new Fite seindow Click File + New File in Spyder. ‘Tne falling cote (sits) inthe new window opened by IDLE | print (Hello Nathan", “Hello. Lalit) Breet] ="Hello Nathan” Breet2 ="Hellotalit™ ‘namel =" Nathan" mame2 =" Lalit" print (greets, greetz) Print ("Hello ™, 1 Manel, *,", nane2) ~ Progress in Computer .2 under Chopter | after Ghopler 1 GETTING STARTED WITH PYTHON LET US REVISE fo © & Python was developed by Guido Van Rossum in February 1991, | & Python offers following advantages 2 exy touse D expressive > complete > cross-platform © {ree and open source + Python also has these limitations ¢ 2 Not the fastest language > Lesser libraries than C, Java, Perl > Not strong on Type-binding. In Python, one ean work in two different ways : (i) Interactive mode, (Ii) Script mode. Interactive mode docs net save commands in form of a program and also, output is sondwiched between commands. Interactive mode is suitable for testing code. % Script mode is useful for creating programs and then run the programs later and get complete output Python is an interpreted language. Python's interactive interpreter is also called Python Shell. Solved Problems Ce EEE See ey Who developed Python Programming Language 2 Solution. Guido Van Rossum in 1990s developed Python programming language. 2. Is Pythan an Object Oriented language ? Solution. Yes, Python is an Object Oriented language. gh level language", What docs it mean to you ? means it is programmer-friendly i.e, easy to program 3. ‘Python is an interpreted hi Solution. ‘Python is a high level language and comprehend. ‘Python is an interpreted language’ means it requires an interpreter (not compiler) to execute its code line by line — one statement at a time. 4. Python programming language got its name from which show. Solution, Python programming language was named alter a British TV show namely ‘Monty Python’s Flying Circus’, 5. What does a cross platform language mean ? Solution. A cross platform language means it can run well on variety of platforms like Windows, Linux/Unix, Macintosh etc. etc. 6 Python is a Free and Open Source language. What do you understand by this feature ? Solution, It means ~ to download Python, one needs not pay anything, because il is Free. And its source-code is also available, which can be modified/improved etc., because it is open-source. statements, COMPUTER SCIENCE WITH python ? 1 ctorier thon prompt (C8., 255 op ; ae shows the resultthereqwte| — Ass%5 aes yexensionendare | — orally with -Py exter” mK areoxca ener as Pylon Script oF Paton re n ane (Take mec arpever) 2° facing, chaees and. ; vt iam savers scl OS ge reson: ok the eorect tpt fo He (a) Tiss sample PSTN ake every chance 4 Drop every Fear () Such as Take every chance. Drop every Fear. to output si (9 Take every chance. Drop every fear. Solution. The correct output is () ‘Reason being : the code Lines beginning with a+ sign are comments. ‘They are just for information, and ignored by the Python interprcter. Hence, the third line ¢print ("Such as") will aso be ‘ignored by Python interpreter. Thus, the Python interpreter will give output of only print) . Wich of the following are not valid strings in Python 2 (9) “Hello” (by 'Hello’ —(@) “Hello” (a) “Hello” sa , Tution. Stings (9, (4) and (e) are not valid strings in Python (c) {Hello} crn STARTED WITH PYTHON oA cooper 1 GF MT: pesignmenls tea m, /Conceplual Questions ‘A: Short Anserer Queslions lon as a programming, Type wher seas Python released ? ci which two languags who was Python's developer an ses contributed to Pyth | language ? | 5, avhat sa erosplotiorm stare? | hot ate he advantages of Pon programming langue ? |B Matar some limitations of Python programming IanBs2k F ahow many different ways, can you work in Python 7 F anat an advantagesdisadvantages of working i Interactive mode in Python ? Fata the advantagestlsndvatages of working in script mode in 19 hon ? Type B : Application Bosed Question 1L. Write instructions to get the following result: path is Fun so don’t be resistant just learn the rules, the rules are consistent ‘Andmost important, you must be persistent | Adding fractions, get conmon denominators. Multiply by missing factors to get the denominators. ‘Add nunerators only, NOT denoninators- mode. Do it in both interactive mode and 5 a " “is Chaaoter 21 www.worldvideweb.com a Python Fundamentals | \ 2.1 Introduction Barebones o! a Python Program 2.2 Python Character Set 2.5. Variables and Assignments, 23. Tokens 2.6 Simple Input and Output INTRODUCTION You must have heard the term IPO - Input, Process, Out} and computer actions are governed by IPO cycle. That Processing and an Output. (put. Most (in fact, nearly all) daily life is, there is certain Input, certain kind of Do you know that programs make IPO cycle happen ? Anywhere and everywhere, where you want to transform some kind of. input to certain output, youhave some kind of input to certain output, you have to have a program. A programisa set of instructions that govern the processing. In other words, a program forms the base for Processing, In this chapter, we shall be talking about all basic elements that a Python can contain. You! be koming stout irs bss NES ssn GIL So, are We all ready to take our first sincere step towards Python Programming ? And, here we go ->). ! COMPUTER SCIENCE WITH PITHON be ; ER SET 2.2 PYTHON CHARACT! sami digit or any other symbol, Python supports Unicode encoding standard, That mens y letter, digit ora tl Ba kas the following character set : GD, TOKENS Ina passage of text, individual words and punctuation marks are called tokeuts or lexical units or Jexical elements. The smallest individual unit in a program is known as a Token ora lexical unit, Let us talk about these one by one. 2.3.1 CREB Python programming language contains the following keywords : False assert del for in or while None break elif fram is Pass with Truc class eee global lambda raise yield and continue except — if nonlocal return as def finally import not ty 2.3.2 elders REED Tent ing le oF Pyhon ateWaig LGR Kaew > © An identifier is an arbitrarily tong sequence of letters and digits. 2: PYTHON FUNDAMENTALS, © Identifiers are unlimited in length, Case is significant tc, Py! treats upper and lower-case characters differently. _© An identifier cannot contain any special character except for underscore (_) The following are some valid identifiers : thon is case sensitive as it byfile DATES_7_77 —22Tz9 Ree ‘python sensitive as MVFILE = _ps _HO13_1K {teats upper and Jonerese HK FILE13 “characters differently. } The following are some jnvalid identifiers : DATA-REC contains special character (hyphen) (other thon A - Z, a+ z and _ (underscore) ) 29cLcT with a digit break My. file © ws speeial character dot (.) 23.3 Literals / Values Literals (often referred to as constant-Vatues) are data items that have a fixed value. Python allows several kinds of literals : (a String literals (ii) Numeric literals (si) Doolean literals (i) Special Literal None (v) Literal Collections 2.3.3A Sting Literals The text enclosed in quotes forms a string literal in Python. ; For example, a’, ‘abe’, “abe” are all string literals in Python, 5 © many other languages, both single character ' £ enclosed in quotes such as “a” or x’ of multiple characters 1. What is meant by token ? Mame the enclosed in quotes such as “abc” or ‘xyz’ are treated as tokens available in Python. String, literals, 2 What are keywords ? Can keywords be wed as identifiers ? As you can notice, one can form string literals by enclosing texi in both forms of quot ~ single quotes or double 3 What 1s an ientifier ? What are the quotes, Following are some valid string literals in Python : identifier forming rules of Python ? - 4. 1s Python case sensitive 2 What is ‘astha’ wRizwan® | __ meant by the term ‘case sensitive’ ? HelloWorld = “Any’s* i = ps 5: Which of the following are valid "129045" Eyton, one, - Adentifiers and why/why i: "Lex-0-w-25" Aiterals by enclosing text Data_rec, data, 1 data, datat, my.file, * “ sata, 1 data, data, 112F60291 | AL switch, lambda, break ? i phiceeha Python allows you to have certain nongrap hie s those characters that cannot be typed return etc, (No character is typed whet pressed, only some action takes place). nm the: A string Iiterol is a es » An Sequence of voresentci sing escape sequences. characters surrounded, care nents ted by abacslath (\}followed by Gngle or double crenata cecapesequenceis ype mt ‘one or more characters. Following table (Table 2.1) gives a listing of escape sequences. Table 2.1 Escope Sequences in Python t cannot be typed directly fro" These nongraphic- COMPUTER SCIENCE WITH PrTHigg, in String . Nongraphic eh, crs in String values. Nongraphic cha, m keyboard e.g., backspace, tabs, keys are racl act nig, Rs. Escape ] ‘What It does Escape What It Non-graphic ch sequence [Non graphic character] _seawence_ | f oe Sante) W Badkslash (\) \r | Carriage Return (CR) y Single quote ¢) \t Horizontal Tab (TAB) ingle quote : ' ot Character with 16-bit hex val i Double quote () — | | xxx (Unicode only) < all (BE Uren | Character with 32-bit hex value \a ASCH Bell (EL) Vixen | charater ih SU : \b ASCH Backspace (5) Ww } | ASCH Vertical Tab (VT) ve | ASCH Formleed (1:1) \o00 | Character with octal value 000 \n New line character \xhh | Character with hex value hh \Winame] | Character named name in the \| Unicode! database (Unicode only) In the above table, you sce sequences represer from the keyboard but when used without have a special purpose, however, if these are be used. (In Python, you can also directl inside a single-quoted string and vi valid string in Python) String Types in Python Python allows you to have two string types : ( Single-line Strings (ii) Multiline Strings quotes (“" one line. To understand this Textis ‘hello there* 1. Unicode and ASCH ' sei Gerad encodings suse teria Chapter oa ep : cape sequence, these carry type a double-quote nting \,', "Though these characte! can be typed special meaning and itis, then escape sequences should to be typed as An escape sequence repre! a single character and h ‘consumes one byte in are normally single-line strings, ie., they must terminate it this, try typing the f fing i ee : { i oe ncGeno BX St Desathor seat | : I (2): tenth = * File “elpythoninpat 24981776900", Line Tenth e helio Symtextrror: €Ot while scanning string Htersl telly EOL means End of Line The reason for the above error is quite clear ~ Python by default creates single-line strings with both single or double quotes. So, if at the end of a line, there is no closing quotation mark for an opened quotation mark, Python shows an error. (i) Multiline Strings. Sometimes you need to store some text spread across multiple lines as one single string, For that Python offers multiline strings. Multiline strings can be created in fw ways : (0) By adding a backstash at the end of normal single-quote 1 double-quote strings. In normal strings, just add a backslash in the end before pressing Enter to continue typing text on the next line. For instance, Text ='hello\ Do nor inert when cutinuig WORLD AA tite tr eat neuf A basic string must be completed on a single line, oF continued with a backslash (\) as the very last character of a line if itis to be closed with a closing quote in next line, : Following figure shows this ‘Even though wnttan ih two ines (Separating with 3), the toxt is ‘considered continuous. That i tring ‘Adding a backslash Q) atthe: fend of tho Tino allows you to hello ontinue typing text in nat ine, sorls Do not forget to close the would be considered as ‘helloworld” string by having a closing Display the string variable to see it quotation mark, ‘yourself, ‘Give commands noxt fo Inf: prompt Nei give output in Out: tne COMPUTER SCIENCE WITH PITHO,, (No backslash fom marks: é “sec in triple quotao# MONE ermine (e) By tying te tet i ales 1 ation marks tthe real sng tHe OE on marks will lorutble tot string by errno wine TO p thain triple 3P0s work), werle. There T Conel!! aw ol In [a]: print st Nelle Worle This is another multiline string. nol: Size of Strings Python determines the size of a string as the count of characte! string “cbc” is 3 and of ‘ within it, then make sur examples given below AY ‘abe "\ab* si Any’ For example, ‘Mutiine siA°8 seated wih tree ania cles eseangonwet on cesed) stri="""Hello World. ‘There Come I! Cheers. 7] pase noe : re mine sng Or str2="* "Hello world. This is another multiline string. 2) Tauline st wit theo (opening ting created sipgle quotes and closing) 7 $ in the string. For example, size of ie 5. Bat jf your string literal has an escape sequence contained le escape sequence as one character. Consider some eis (\\is an escape sequence to represent backslash) ize is 3. ize is 2 (\ris an escape sequence, thus one character eis 4 1on allows a single double quod gone ote (thou escape sequence in ind vice-versa, For multiline striny character at the end 0 ng SE stra bos | be then size of the string char For multiline strings created v fine, while calculating size, the backslash cannot put EOLs using return key in single! Ste ='a\ by ° | ‘The size of string Str4 is 3 (only 3 characters, To check the size of a string, you may al hon prompt in console command on the P3 [eter -eorrten wort I wer 2.3.38 Numeric Literals int Gigned integers) lat (Noating point real values) complex (complex numbers) cuoewe 2 FUTON FUNDAMENTALS ge created with triple quol fie line ds also courted i ade ew sir3 is 5 (three characters a, & rs a and [respective shown in the following figur ax promi gy cee Te [a]: sto =e a5 LOL (end-of-line) created a while calculating, size the size, For example, enies heh are econ Ci Pd ef T0%) cand two EOL characters that follow th single/double quotes and backslash character at end of the ove nat counted in the size of the string ; also you ‘double quoted multiline strings ¢f no backslash counted.) - aad | “Use len{cobject name>) to get the size or fength of an abject. Iso type len() window shell as Triple quoted multine stings also count EOL charactors in the size of the sting. Single!couble quoted strings typed in multiple ine with Vat the end of each intermediate line do not count \ in the size of the string strt = Len(Ste3) lent Ste; Triple quoted muttiline strings ‘count EOL characters in the of the string but do not cou backslashes ( \ ) at the end « Line 5S intermediate lines, Encoding U8 og Thenumericliterals in Py el f ic literals in Python can belong to any of the following four different numerical types: often called just inte; i it gers or ints, are positive or negative wl numbers with no decimal point, ® positive or negative whole floats represent real numbers are written with a decimal poi a ers and are written t i" . . cimal a of the form ab where @ and b are floats and J (or j ) represents , an imag en). ais ree vam ary umber ais the real part of the number, COMPUTER SCIENCE WITH Pre Let us talk about these literal types one Py one: Integer Literals / ; Integer literals are whole numbers without any hia constants has been specified in the following rule + igit and must not contain any decimat i t must have at least one digi ¥ See cealn either (+) or (-) sign. A number with no sign is assumed to be poritive. Commas cannot appear in an integer constant. fractional part. The method of Writing inte. Python allows tree types of integer literals : 7 () Decimal Integer Literals. An integer literal consisting of a sequence of digits is taken yg decimal integer literal unless it begins with 0 (digit zero). For instance, 1234, 41, +97, -17 are decimal integer literals. (i) Octal Integer Literals. A sequence of digits starting with 0o (digit zero followed py letter 0) is taken to be an octal integer. For instance, decimal integer 8 will be written as 0010 as octal integer. (89 =10,) and decimal integer 12 will be written as Ool4 as octal integer (12y9 = 144). ql ‘An octal value cau contain only digits 0-7 ; 8 and 9 are invalid digits in an octal number ig, 0028, 0019, 00987 etc, are examples of invalid octal numbers as they contain digits § and 9 in them (iii) Hexadecimal Integer Literals. A sequence of digits preceded by Ox or OX is taken to be an hexadecimal integer. cam For instance, decimal 12 will be written as OXC as ae hexadecimal integer. Manyleeee i Thus, number 12 will be written either as 12 (as decimal), such as G CH, and even Oo14 (as octal) and OXC (as hexadecimal). 2xtoo have two types forinteg A hexadecimal value can contain digits 0-9 and letters te ql tees) Ses A-F only ic, OXBK9, oxPQR, OXIIAZ ele, are examples of 3. ly B Iples ¢ x, there is only one Inte invalid hexadecimal numbers as they contain invalid type that works letters, i.c., Ietlers other than A- long integers and can supp small and big integers. Floating Point Literals Floating literals are also called real literals. Real literals are numbers having fractional parts These may be written in one of the fo forms called Fractional Form or the Exponent Form. 1. Fractional form, A real literal in Fractional Form consists of signed or unsigned digit including a decimal point between digits. The rule for writing a real literal in fractional form is : A real constant in fractional form must have at least one digit with the decimal point, either before or after. It may also have either + or —sign preceding it. A real constant with no sign is assumed to be positive. The following are valid real literals in fractional form : 20, 175, -13.0, - 0.00625, .3 (will represent 0.3), 7. (will represent 7.0) Choptee 2 = PYTHON FUNDAMENTALS ‘The following are invalid real literals : 7 (No decimal point) +1712 (itt 17,250.26.2 (Two a 17,250,262 (comma not allowed) 2, Exponent form. A real literal in Exponent form consists of two parts : mantissa and exponent. For instance, 5.8 can be written as 0.58% 10" = 0.58E01, where mantissa part is 0.58 (the ‘ponent part is 1 (the part appearing after E). ED] represents 10" . part appearing before E) and ‘The rule for writing a real literal in exponent form i ‘A real constant in exponent form has two parts ; @ mantissa and an exponent. The mantissa must be either an integer or a proper reat constant. The mantissa is followed by a letter £ or e and the exponent, The exponent must be an integer. The following are the valid real literals in exponent form : 152E05, 1.52E07, 0.152E08, 152.0808, 152E+8, 1520E04, -0.172E-3, 172.E3, 25E44, 3.£3 (equivalent to 3.03) (Even if there is no preceding or following digit of a decimal point, Python 3.x will consider it right) ‘The following are invalid real litcrals in exponent form 17E (No digit specified for exponent) 0.17623 (Exponent eannel have fractional part) 17,225802 (No comma allowest) [Do read following discussion after it] Numeric values with commas are not considered int or float value, rather Python treats them as a tuple. A tuples is a special type in Python that stores a sequence of valves. (You will learn about tuples in coming chapters ~ for now just understand a tuple as a seqieuce of values only. ) } In [2]: & = 17,225€02 J The last invalid example value given above (17,225c02) asks for a special >——— mention here. Ta, [212 a= 24998 Python gives ne error when, you assign a numeric value ‘with comma init, Any numeric value with a comma in its mantissa will not be considered a legal floating point number, BUT if you assign this value, Python won't give you an error, The reason being is that Python will not consider that asa flonting point value rather a tuple. Carefully have a look at the adjacent figure that illustrates it. We are not talking about Complex numbers here. These would be discussed later when the need arises, In 3]: typela) out [3]: tuple Python will not consider the numeric values with, ‘commas In them a8 ‘numbers (Int or float) BUT as atuple-a sequence of values In (4: typo(b) Out (4): tuple In (SJ: | Out($}: (1, 234) In (6): & Out(6]: (17, 225¢0.6) COMPUTER SCIENCE Wit 23.3C Booleon Literals ‘A Boolean literal in Python i Boolean values i, True (Boo! ‘A Boolean literal can either have 5 used to represent one of the two Jean truc) or False (Boolean false). value as True or as False. 2.3.30 Special Literal None Python has one special literal, which is None. The None literal is used to indicate absence of value. It is also used to indicate the end of lists in Python. © Valued The None value in Python means “There _[Out[15): 10 is no useful information” or “There's nothing here.” Python doesn’t display anything when asked to display the value of a variable containing value as None. Printing with print statement, on the other hand, shows that the variable contains None (see figure here). to (16): Value2 : print(Value2) Python supports literal collections also such as tuples and lists ete. But covering these here would make the discussion too complex for the beginning. So, we'll take them at a later time. special literal None “ares built-in constants (ie Python. BASICS ABOUT TOKENS 66 P Progress In Python 24 Start Spyder IDE through Anaconda Navigator or any other IDE af your choice. 1. In front of the Python prompt In I: in IPythonConsote, 1 the same order. pe the following statements one by one, (@) Write the expected result and then write the actual result that Python ret () Do write the rea: femoral 'son(s) behind the result returned by Python. Solved Sample Statement to | Expected | Actual betyped | result | ‘result Reason abe123 =25 nothing abc123 3 noth vt sig ing | Python internally assigns the value to abcl23 but shows nothing. Value of abc123 is displayed on screen, Proctically doing it on the computer, Do>incce Chopler 2 + PYTHON FUNDAMENTALS Reet : = 2.3.4 Operators Operators are tokens that trigger some computation when Tied to variables and other objects in an expression. {a wat are Uterals ? How many types of | Uterals are available in Python 2 ‘2. How many types of integer literals are allowed in Python ? How are they written ? The following, list see . brief description of the 3. Why ae chanel Vis Fant ub Ped operators and their functions being ess , Joperators, in details, will be 44. Which escape sequences represent the covered in next chapter - newline character and backspace Data Handling. character? An escape sequence : represents how many characters ? Cres Unory Operators 5. What are string-literals in Python ? How many ways, can you creste String @(@IGpGratelupons Following are some unary operators : literals in Python ? Are there any differences in them ? 6. What is meant by a floating-point literal in Python ? How many ways can a floating literal be represented into ? 2. Write the following real constants into. Binary Operators exponent form : 23.197, 7.214, 0.00005, 0.319 8 Write the following real constants into fractional form : i 0.1306, 0.417E-04, 0.¢E-5, Arithmetic operators 12602, 12.602 9, What are the two Boolean literals in Python 2 40, Name some built-in literals of Python. 11. Out of the following literals, determine their type whether decimal / octal / hexadecimal integer literal or a floating point literal in fractional or exponent on Bitwise operators form or string literal or other ? 123, 00124, OxABC, ‘abe, “ABC’, & _Bitwise AND 12.36, 036-01, “Itoh”, © Bitwise exclusive OR (XOR) None, True, False 1 Bitwise OR 12. What kind of program elements are the Shift operators (vs aos mint << shift left oSSNes : >> shift right 13. What will var and var2_ store with statements : var = 2,121E2 and Identity operators Var2 = 0,2,121E2 ? What are the types i is the identi s is the identity same ? ‘of values ste 2 tored in vari and var2 ? is not is the identity not same ? os Less than ss Equal to t= Notequal to Logical operotors 2.3. COMPUTER SCIENCE Wt ayy F 4 : Assignment operators Assignment J= — Assign quotient 4= Assign sum +2 Assign product | oye Assign remainder = Assign difference se Assign Exponent J/= _ Assign Floor division Membership operators in whether variable in sequenge notin whether variable not in sequence and Logical AND or Logical OR More about these operators you will lean in the duv course. Giving descriptions and exampta is not feasible and possible right here at the moment. 5 Punctuators Punctuators are symbols that are used in programming Punctuators 2fe symbols tha languages to organize sentence structures, and indicate the 378 sed mo conby i i o neusees to onpan rhythm and emphasis of expressions, statements, and pene iness anc Program structure. structures, and indicate the rhythm and emphasis gf expressions, statements, and rogram structure. "THVOLIOB, 2.0 = 4 The usage of these punctuators will be discussed when the need arises along with normal topic discussions, Most common punctuators of Python programming language are: LET US REVISE i “4 « + * ° “A oken is the smallest individual unit ina program. Pathan provides following tokens: yor, defn (ames), Values (literals), Punctuators, operators and comments. A keyword isa reserved word carrying special meaning and purpose. Meniffers are the user-defined names for different pars of the rogram, In Python, en tdentifier may contain tetters (@-2, A-2), digits (0-9) and a symbol underscore (J. However, on ‘all fetiersidigits in an identifier are significant. Fython alfows following tuerals : string literal, numeric (in Bool ial : I (integer, floating-point literals, Boolean literals, speci literal None and literal collections). (nese Retina point eal, Booleon Greroors ae tokens thar rigger some computation / action when applied (0 variables and other abjects in em Sirens are smbols used to organize programing. sentence structures ond (ndicate the rhythm and emphasis ‘expressions, stotements and program-structure, ; Choplee 2 : PYTHON FUNDAMENTALS 24 BAREBONES OF A PYTHON PROGRAM Let us take our discussion further. Now we are going to talk about the basic structure of a Python program — what all it can contain, Before we proceed, have a look at following sample code. Look at the code and then proceed to the discussion that follows. Don't worry if the things are not clear to you right now. They'll become clear when the discussion proceeds, # This program shows a progran’s components # Definition of function SeeYou() follows dof Secvou() : ie Comments (begin with @) Print ("Time to say Good Bye 11") # Main progran-code follows now ass ‘Statements b= a-104 Expressions print (a i — . if bos* # colon means it’s a block ¥. -» print ("Value of 'a' was more than 15 initially.") Inline comments SY te inthe middie ofa ined Indentation “2 (ee indented inst, else : “a print (‘Value of ‘a' was 15 or less initially.*) SeeYou() # calling above defined function SeeYou() As you can see that the above sample program contains various components like © statements © function ©} expressions © coriments © blocks and indentation Let us now discuss various components shown in above sample code. (i) Expressions An expression is any legal combination of symbols that represeuts a value. An expression represents something, which Python evaluates and which then produces a value. ExEessIOHSes | ‘An expression is any. legal| combination of symbols that] Some examples of expressions are 15 } expressions that 2.9 o+5 complex expressions that produce a represents a value. G45) /4 J rac ample code, can you pick out all expressions ? Now from the above These are: 15, 2+10, a+3, b>5 COMPUTER SCIENCE WITH PrT}oy, entis mming instruction tha ae pressi mething, a statement is a Progra! ' oy jon represents somell Me same an kes Se Following are some examples of statements ¢ (iello") a this statement calls A statement is 9 progr print function Instruction that does sonnet print Le., some action takes pose if boS: tis executed ie, some action takes place, And yg ted, a statement 1 may not yield a value. is evaluat may While an expression isevaluaed 9 nay 0 not necessary that a statemen! ‘Some statements from the above sample code are? an1s bea-10 print (a+ 3) if b= 50") ack ait [peiiiteer net. ure asat2 este indent a statement ; Python “rabse error for that, ‘While working in Python, one should keep in mind certain style rules andl conventions, In the following lines, 2: we are giving some very elementary and basic style rules fy Statement Termination Python does not use any symbol to terminate a statement. When you end a physical “ code-line by pressing Enter key, the statement is considered terminated by default, ‘Maximum Line Length Line length should be maximum 79 characters. Lines and Indentation Blocks of code are denoted by line indentation, which Is enforced through 4 spaces (not tabs) per indentation level, Blank Lines Use two blank lines between top-level definitions, one blank fine beween, method/function definitions. Functions and methods should be separated with avo blank lines and Class definitions with three blank lines. Avoid multiple statements on one ine Although you can combine ‘more than one statements in one line using, Symbol semicolon (:) between two statements, but itis not re mmended, 2 Whitespace You should alw: ‘ays have whitespace around Operators and after punctuation b V5 rm Ut not with parentheses. Python fonsiders these 6 characters as whitespace." * “at a = ; h pace: * * (space), 1 mee a9 expression in Python 2 (newline), “1 (horizontal tab), \w* (vertical tab), ‘\f" (formfeed) % Wat Se statement in Python? How is | and *y" (carriage return) ‘ astatement different trom expression > 3. What ita comment? In how many wa can you cate connents a Peace 4. How would you create ulti comment in Python ? ‘< What is the diference between flltine (Case Sensitive Python is case sensit ©, $0 case of statements is So Impontant Be careful while typing eade and identifier-names, Docstring Conve ation Com i ii rey Based for doeetngg oe MoMA ple double quotes" comment and inline comment Wdentitier Namin, Fi 8 You ma; & ‘What is a Bock or suite in thon 2 | *idenifereg tone = mans underscores {0 separate words in How is indentation related to it > ist letter of th scl feed CamelCase by capitalizing €9., Loan, Amount or loanAmount CChopler 2 : PYTHON FUNDAMENTALS GP } COMPONENTS OF A PROGRAM of P ———_—<—_—<$___— i Progress In Python 2.2 This is another program with different components def FirstSMultiples( ) : main code Fill the appropriate components of program from the above code. Science with Python and fill it there in PriP 2.2 under Chapter 2 alter € Please check the practical component-book ~ Progress in Computer practically doing it on the computer. pooaece 2.5 VARIABLES AND ASSIGNMENTS A variable in Python represents named location thal refers toa value and whose values can be used and processed during program run. For instance, to store name of a student and marks of a student during a program run, we require some labels to refer to these marks so that these can be distinguished easily, Variables, called as symiboiie variatles, fy serve the purpose. The variables are called symbolic variables gets whose values can because these are named labels. For iustanee, the following fe awed and processed during statement createsa variable namely marks of Numeric type: Program run, are called Variables. marks = 70 2.5.1. Creating a Varicble Recall the statement we used just now to create the variable marks : marks = 78 As you can see, that we just assigned the value of numeric type to an identifier name and Python created the variable of the type similar to the type of value assigned. In short, after the above statement, we can say thal marks is a numeric variable. So, creating variables was just that simple only ? Yes, you are right. In Python, to create a variable, just assign to its name the value of appropriate type. For exaniple, to create a variable namely Student to hold student's name and variable age to hold student's age, you just need to write somewhat similar to what is shown below Student = "Jacob" Age=16 COMPUTER SCIENCE WITH PYTHON Python will internal create labels referring (0 thes: alues as shown below : the lly create labels ferring to these v: il student Age let's now create some more variables. ‘t it simple?? © Okay, ie. : # variable created of String type ; molances e875 # variable created of Numeric( floating point) type routes . # variable create of Numeric (integer) type rollNo = Same way, you can create as many variables as you need for your program, Je way, y IMPORTANT - Voriables are Not Storage Containers in Python i sramming, be having an idea of variables, 5 you have an earlier exposure to programming, you mus! i ca | renin VARIABLES ARE NOT CREATED IN THE FORM MOST OTHER PROGRAMMING LANGUAGES DO. Most programming languages create variables as storage containers e.g, Consider this: | age =15 age = 20 Firsily value 15 is assigned to variable age and then value 20 is assigned to it, Traditional Programming Languages’ Variables Variable is a container in traditional Statement [Variable Sa container in traditional " ramming languages like C, C+, nepes ic, it isa named storage location that / stores a value in it] Variable age is created as a container at a memory address, a: say 202530, and it stores value as 15 in it. Notice memory adulress ocation) of variable Statement ge did not change with change in its value aee= 22, / v Now this statement will change the contents of the location where variable age is created, ic, With this statement, the location of the variable did Rot change, only its contents changed. This is how traditionally variables were created in Programming languages like C, C++, Javaeetc. | ‘ bles, sane ers, ©, Cchopter2 | PYTHON FUNDAMENTALS [ Python's Handling of Variables BUT PYTHON DOES THIS DIFFERENTLY Let us see how Python will do it. Memory has literals/values at defined memory loca memory address, Talelelete nemo’ "oni z0za2 20289 lions, and each memory Jocation has a Tio| (eo a label pointing to memory ariable age will be created as When you give statement age = 15, location where value 15 is stored i, 3 E 7 _- - - fra Gis Tis (a7 hrs (a9 (20 ~ pea} 20282 Does Tai 2088 ] age now referring to focaton 20216 Lat has wave 15 ‘ill not be having the same location as 20, which is at different location ie, And when you earlier, It will now refer to valu [ Sarererea re Mia fas ae (a7 vie 19) (20 20216 120280 20295 ° iow age is referring to location 20296 | @ | ‘age So this time memory location of variable age’s value is changed. ‘Thus variables in Python do not have fixed locations unlike other programming languages. The location they refer to changes everytime their values change (This rule is not for all types of variables, though). It will become clear to you in the next chapter, where we talk about Mutable and Immutable types. COMPUTER SCIENCE VATH PrAhyp, lvalves and Rvalues Broadly fewlue and reulue can be thought of as : Wwolve ; expressions that can come on the Ths (left hand side) of an assignment, walue : expressions that can come on the ths (6 ht hand side) of an assignment, EZR ION values are the objects to 6.8, You can say that you can assign a yal acz expression, Lvalues ean be-10 ths oF rhs of an assign statement. you cannot say But you cannot say Rvalues are the terals 20=a expressions that are assieneg, Feb ERROR Walues. Rvalues can come on, 7 of an assignment statement, or at2=b The literals or the expressions that evaluate a value cannot come on Ihs of an assignment hy they are rvalues but variables names can come on Ths of an assignment, they are Walues, Lvalues can come on ths as well as rhs of an assignment, 7j | 2.5.2 Multiple Assignments In Python, assigning a value toa . ‘ 7 . Variable means, variable’s la Python is very versatile with assignments, Let's see in how Isreterring ta that Vale aan many different ways, you can use assignments in Python : 1. Assigning same value to multiple variables You ean assign same value to multiple variables in a single statement, ¢, =c=19 It will assign value 10 to all three same location with value 10. riables a, b, c That is, all three labels @,b,¢ will refer to 2. Assigning multiple values to mult iple variables You can even assign multiple values to multiple variables in single statement, C8, . %+¥, 2=10, 20, 30 Itwill assign the values order wise, value and so on. That means, abo ‘This style of assi ic, first variable is given first v ve stalement will assign v; ening values is vel ‘alue, second variable the second — ‘alue 10 to x, 20 to yand 30 to = Ty useful and compact. For example, consider the code given | % ¥=25, 50 Print (x, y) Newill print result as 25 so crane 2 PINON FUNDAMENTALS swap values of x and y. you vishaying £0. Now, if you wan print (x.y) Now the result will be 30 25 pecause this time the values have been swap) fh multiple assignments, ‘expression(s) and then 5 and y is having, 50. please remember that Python first ‘assigns them to LHS, €5- ped and xis having value 2 While assigning, values throt evaluates the RHS (right hand side) a statesent1 a,b, c=5, 10,7 a statencnt? bye,anard, ber, c-2 print (a, b, c) band c respectively © Statement] assigns 5, 10 and 7 toa, +2, ¢-1 which will yield © Statement? will first evaluate RUS ie, a+ 1, 541, 1042, 7-16, 12,6 “Then it will make the statement (by replacing the evaluated result of RHS) a5 + bc, a=6, 12,6 Thus, b= 6, ¢= 12 and a=6 © The third stalement print (a, b, ¢) will print 6612 Isn't this easy ? Now can you guess the output of following code fragment? pega, q, r=p-2, p+2 print (p,q, P) Please note the expressions separated with commas are assigned in same order ¢g., x=18 yy Y= x42, x45 will evaluate to following (after evaluating expres evaluated from left to right and ions on ths of = operator) Ye y=42, 15 ie, firstly it will assign first RHS value to. first LHS variable ie., y=12 then it will assign second RHS value to second LHS variable i.e. yeis So if you print y after this statement y will contain 15. 2, The output should be COMPUTER SCIENCE WITH PYTHON ess the output : Now, conser following code and Bue the out x) #20, 30 yy exei0, print (x, ¥) Well, it will print the output as 30 50 Now you know why 7@ x+20 is create! when you first assign a value {0 it until some value is assigned to de fragment. Try running it in script mode : 2.5.3 Variable Definition 0, you see that in Python, a variable It alco means that a variable is not created To understand it, consider the following © print (x) x=20 print (x) When you run the above eode, it will produce an error for the first statement (line 1) only ~ name ‘x’ not defined (sce figure below) tee eirornertror 2% remerese Bled a ewe | Tn (2): runfile(t sy! a wdine' [Python Work") Traceback File “cipythoneingut-1-cO3RGoFdd35", Line 1, in [Python hark/Ma.py", wdir=*E:/Python Work") File “C:\Prograndata\anaconda3\ib' \sitecustonize.py", Line 705, im runt te-packages\spyder\utils\site Fale "C:\PrograsOat\anaconda?\Lib\site-packages\s ragitecustonize.py", Mine 102, in execfile ees Napran\ut Lis\eite ead(), filename, ‘exec'), namespace) | Nanoterer: ‘x! As not defined BS The reason for above error isi e or is implicit. As you kn i ™ foraben i }ow that a variable is not ere it i simt th Sisetee ‘variable is not ereated until some value is (undefined) variable results into error, B printed in ine 1. Peinting/using an So, to correct the above code, y ‘ eee @ you need to first asi; i, ‘0.x before using it in a statement, somewhat i something : | x=8 print (x) x=20 print (x) Now the above # variable x created now code will execute without any error, Caution with Dynamic Typing “Chaplet 2+ PYTHON FUNDAMENTALS 2.5.4 Dynamic Typing value (ofa particular In Python. a8 you have learnt, a variable ls defined by assigning toit some value (Of 2 Part : type such as numeric, tring ete.) Far instance, after the statement X10 We can say thot variable x is referring to a value of integer tyPe- \ue of some other type to variable =, in your program, if you reassign a val Python will not Late Complain (oo error wil be raed), e xe18 IT prin a certain type, can be made to. Ke Welio boris" tea erate ol weirene ype Tat eae int « : a) Dynamic Typing. ‘Above code will yield the output as = 30 Helo World So, you can think of a Python variable as labels associated with objects (literal values in obr case here) ; with dynamic typing, Python makes the label refer to new value (Fig. 2-1). Following figure illustrates it inet x=20 X= "Hello World” Tee Sein G Werls Figure 2.1. Dynamic typing in Python variables, s first pointing tofreferring to an integer value 10 and then Asyou can see in Fig. 2.1, variable toa string value “Hello world”. Please note here that variable X does not have a type but the value it points to does have a type. So you can makea variable point to a value of different type by reassigning a value of that type; Python will not raise any error. This is called Dynamic Typing feature of Python. Although Python is comfortable with changing types of a variable, the programmer is responsible for ensuring right types for certain type of operations. For example, X=16 tepal, became nwo integers can ee ema a tee v2 Poston is comfruable with X= ‘Day tai pi Y=X/2 <——— ERROR? a saring carmnot be divided, COMPUTER SCIENCE WITH PrTjicy, eed to ensure that variables with right used in expressions. ofa variable i.e, what type of type() in following manner: So as programmer, you type of values should be Ifyou want to determine the type value does it point to ?, you can use type (>> a=10 >>> type(a) The pe retuned as int Giateger) et >>>. a= 20.5 >>> type(a) . The ne returned as float —— [henne pint mnie) 3 >>> a="hello” “ >>> type(a) Use type () ids that jpport static typlr ; to determine the type of €E1855°St> areal a ing object. Object can be a va >>> or a literal etc. e 2.6 SIMPLE INPUT AND OUTPUT In Python 3.x, to get input from user interactively, you can use built-in function input( ). The _ function input( ) is used in the following manner : vartable_to_hold_the_value = input (" Vv Typeeror: must be str, not int = int( input ( ) ) «variable_nane> = float( input ( your age ? Mot 4 your age 3 Te Be ST Troceback = ees i Tcipython. input 23: 460b 2176 she! jaluefrror: invalid Literal f int() with ba: ° je» intl input(-nnat is your age? =) ) inet ts your one \Ggrantesh end= ‘\n’ or ps a separated objects to be printed. ion is as follows : print(*objects, [ se} “objects means it can be one or multiple comm: Let us consider some simple examples first : print ("hello") print (17.5) #a number print (3.14159*(r*r)) # the result of a calculation, which will #1 be performed by Python and then printed # out (assuming that some number has been # assigned to the variable r) # multiple comma separated expressions a string print ("I\’m", 12 +5, "years old.” Consider some examples with outputs : Example statement 1: Example statement 2: | Example statentent 3: ",243) a=25 print ("Double of",a, "is", a*2) will print the output as follows (a"2 is evaluated and its result is 5 printed) : ' Double of 25 is 5@ print ("Python iswonderful.") | print (“Sum of 2and 3 is’ will print the output (243 is evaluated and i printed as 5): j Sumof 2and3isS will print the output as: Python is wonderful. Now consider some more print statement examples : print (obj) print (obj, obj2, obj3) print( ) print (‘Object1 has nore value than Object2' 2 print (obj1, ‘is lesser than’, obj2) ali The output of these print, i ] Print( functions, you'll be able to determine if the values of variables obj, obj1, obj2 and obj3 are kn int() wi oi sips "9 are known to you. (A print() without any value or name or expression prints | 3. Insyntar, elements in square brackets mean that they are ootlonal. mo he | pyTHON FUNDAMENTALS int stoloment Pe statement has 3 number of features ¢ int its the items to strings ic. if you are printing a numeric value, ft will lent string and print tj for numeric expressions, it first into equival n ive sl to sting, before printing (as it did in example onvel it ly convert it tems that you give, must be convertible to string (ype, 1] our discussion so we have piven examples of using dix B. Please do refer to Appendix 1. IMPORTANT Wal print(), the objects/i es may deral covering there with exam print ) with different (Pes ‘of arguments in Ape it inserts Spaces between items automatics lly becau i wet ine ep argument specifies the oP ator character. The print() automatically adds TResep character between ne ras/abjects being printed in aline. Ifyou donot giveany value for sep, then by default ihe print( ) will add a space #9 between the items when printing. Consider this codes Lunar diferent string objects with rm pce in therm are being printed, print ("My" “name”, "is", “Amit. )* the default value of sep argument is will print Bur the output tine bas automatically spacer inserted In —— enwven there becuse default sep character (sa space my nase 15 anit. * You can change the wale of separator haracies with sep argument of print() as per this: ‘The code: print (MY"» spare", “is”, “Anit.", Sep" "++ will print print) pura the ems ep oaraster, which is my. .enane. © 1S++ 4 newline character at the end of the fine unless you pive your own end ver below : 6 it appends argument. Consider the code s print (“My nane #5 Anit.") print(*Zan 16 years old”) Rwill produce output as elt old My mane ts Tan 16 years So, aprint) statement appended a newline at the end of objects it printed, ie, in above code: vontically anddea a newtine character J fine printed so that the next im the new fine Pynane is Anit. Jor \n +—__ Tam 16 years old. inthe prints J pe The print() works thi : by ear works this way only when you have not specified any end argument with itbecause wy default print{ ) takes value for end argument as ‘tn’ ~ the newline characte, Fagin fave a a, : isa character used to represent the end of a Line of text and the = you explicit and end it wil print( seill print output 35 : myname is Anit. $1 am 16 years Sol soe fig printed at the end of print line. Code fragment 1 a, b= 20, 30 Noe fist pint print (‘a=", a, end=‘*) } a frotement has end was a space print ("b =", b) Now the oul a=20b= 350 eu 1. What is a variable ? 2. Why is a variable called symbolic variable 2 3. Create variables for the following (Oto hold a train number {ito hold the name of a subject (i) to ld balance amount in bank account (ii) to hold a phone number } 4. What do you mean by dynamic typi of a variable ? What is the canti ‘must take care of 2 | What happens when you try to aocez: the value of an udeii =F & What is wrong with the feltee: Statement ? Jy give an end argum ore otring specie” “my name is Amit. 7 print(*xan6 years old. he end argument determines the tput produced will be like : ‘This space i because of ead = COMPUTER SCIENCE WITH PYTHON = Xt va the print() will print the Tine it 1() function ther ent with a print() fu the prin with the end argument, 6S end = “$") rs tme the print(? ended the fine wie Fre ta ehoracter. which 8S" bee old. end character that will be sin pris) ‘The reason for above output is quite clear. Since there is end character given as a space (i¢,, end =" *) in first print statement, the newline (‘\n') character is not appended at the end of output generated by first print statement. Thus the output-position-cursor slays on the same line. Hence the output of second print statement appears in the same line. Now can you predict the output of following code fragment ? 1 Name = ‘Enthusiast’ print ("Hello”, end = *) print (Name) print ("How do you Find Python 2") Well, you guessed it right. © It is : Hello Enthusiast How do you find Python ? Pion you can break any statement by putting a dfatement ene Enter key, then completing le. For i = example, following statements Print (“Hello™, \ <———— The backslash at the end end=** ) that the statement is continuing in ext Tin Now consider followi following sample prosrame eras ee 2 PYTHON FUNDAM owe Program to obtain three numbers ond print their sum, 2.1 joan fund = Ant( dnput(“Enter nurber 1: “)) nun? = int( Anput “Enter nunber 2 : “)) rund = Ant¢ Anput ("Enter number 3: “)) Sum = qund + nad + numa print("three numbers are : “, num, mun2, num3) print("Sum 4s :", Sum) The output produced by above program is as shown below : enter number 1: 7 enter number 2: 3 enter nunber 3: 13 three nunbers are: 7313 sun is: 23 Prograni to obtain length and breadth of a rectangle and calculate its area, # to input length and breadth of a rectangle and calculate its area length = float( input("Enter length of the rectangle : ")) breadth = float( input(“Enter breadth of the rectangle : ")) area= length * breadth print ("Rectangle specifications ") print ("Length=", length, end = «*) print ("breadth =", breadth) print ("Area =", area) The output produced by above program is as shown below Enter Tength of the rectangle ; 8.75 Enter breadth of the rectangle : 35.0 Rectangle specifications Length = 8.75 Breadth = 35.0 Area = 306.25 2.3 Program to calculate BMI (Body Moss Index) of a person. Body Mass Index isa simple calculation using a person's height and weight. rogram The formula is BMI = kg/m? where Ag is a person's weight in kilograms and m? Is their helght In ‘metres squared, # to calcusate BMI = kg /m square weight_in_kg = float(input (“Enter weight in kg : ")) eee P COMPUTER SCIENCE WITH PYTHON, float(input (“Enter height in meters : ")) pelt in_meter * height_in_meter) bai = weight_in_ke / ( height_t print("BMr is: ", bmi) “The output produced by above program is as shown below : enter weight in kg = 66 Enter height in meters : 1.6 pur is : 25.781249999999996 ) / VARIABLES, SIMPLE I/O Progress In Python 2.3. 6 pelleiicieed dallas ee ~aiP Start a Python IDE of your choice 1. Click File -» New File... and type the following coite into it : nyNumber = 10 print (myNunber +1) print (myNumber) # output statement 1 # output statement 2 Science with Python and fill if there in Pri? 2.3 under Chapter 2 after practically doing it on the computer. € Please check the practical component-book — Progress in Computer LET US REVISE et * Paton progrom can contain various components lik expressions, statements, comments, functions, blocks and indentati An expression is @ legal combination of symbols that represents a value, % A statement is a programing instruction. Comment are roc-executable,adlional information added in program for readabitiry, {In Python, comments begin with a # character, Comments ingte-tin ir kt ails S ean be si ingle-line ‘comment, multi-line comments and inline comments, ; i a named code tht con be reused witha program, Ba 7 7 A Hocuteode block 2 Grup of statements that are part of another statement, © Blocks are represented through indentation, : ° F A voriable in Python is defined only when some value is assigned to it. & Pathon supports dynamic 1 Yping i. a variable ca Fag hhMt it3e tin ipa rom wees ovogs nL ete DCEO ferent times, Output is, i always returns a suring Sereated through print) by cating pring Protea "9 9p of value, Nom as the difference xs It gasp 8 meaning and purpose. Keywords are rescrved Slaton He rename i else ct. ave keywords. aa usredfined name given ta pat of a program ois. warile, objec function et. denier Fo aregerved, These ate defined by the wsce but they can have leer digits and a | estes recy must begin with thr eller or underscore, Fornsanc, has, ri sara tras in Pl? ec my ps of eas ar lowed in Python? 2 Mt Lirals mean constants, the data toms that never change ther vue during program 5 Setup lows ie types of ites = (String literals (i Numeric lite (ii Boolean lite (ie) Special Literal None (0) Literal Collections like tuples, lists ete spresent an integer literal ? als 43. Howe many ways are there in Python to Solution, Python allows three types of int (@) Decimal (base 10) integer literals (8), Octal (base 8) integer literals (6 Hexadecimal (base 16) integer literals {@) Decimal Integer Literals. An integer literal consisting of a sequence of digits is taken to be decimal integer literal unless it begins with 0 (digit zero). For instance, 1234, 41, +97, ~17 are decimal integer literals. (4) Octal Integer Literals. A sequence of digits starting with Oo (digit zero followed by letter 0) jis taken to be an octal integer. For instance, decimal integer 8 will be written as 0010 as. octal integer. (6jp =10,) and decimal written as Oold as octal integer (1249 =14)- | (0 Hexadecimal Integer Literals, A sequence of digits preceded by Ox or OX is taken to be an hexadecimal integer. For instance, decimal 12 will be written as OXC as hexadecimal integer. ‘Thusnumber 12 will be writlen either as 12 (as decimal), 0014 (as octal) and OXC {as hexadecimal). er 12 will b 4. What wl be the sizes of following constants : MXY YL MEXYL > Na, "a", Reema\’s", "VW", "it’s", , We ier Solution. ‘a’ Size is 1 as there is 1 character (escape sequence) and it is a string literal enclosed in single quotes. : “a Size is 1 as there is 1 character enclosed in double quotes. COMPUTER SCIENCE WITH PYTHON =X! 7 characters enclosed in double quotes. (Vis red a single character.) se it sa string having 7 cha Yor apostrophe and is conside' ; sracter constant and is containing just one character vv. double quoted string without escape sequence ina quote e reuenee ina single quoted string ¢g., "No." Ttag’. speena\?s” Size is 7 becaut escape sequence size is 1. It isa chi sits* ize is 4, Python allows single quot ald Sie Mdouble quote without escape seque with \ in the basic string. “er ae is 4 tis a multi-line string create xy ., ye si aracter is also counted in size. aes Size is 5: Triple quoted multi-line string, EOL (-) ch | Hore many types of strings are supported int Pyllion 2 Solution. Python allows tteo string types + () Singtestine Strings Strings that are terminated in single line (i) Multi-line Strings 5. How caw you create multi-line strings in Python ? Solution, Multi-line strings can be created in tivo ways = (@) By adding a backslash at the end of normal single-quote or double-quote strings ¢.8. Text= "Welcome \ To\ Python” Strings storing multiple lines of text. (0) By typing the text in triple quotation marks. (No backslash needed at the end of line) ¢.g., Str1="""Welcome . To Python . What factors guide the choice of identifiers in programs ? Solution. ()Anidentifier must start with let ‘ with a letter or underscore followed by any number of digi ya f e Ne reserved word or standard identifier should be used , re eandiele (ii) No special cha bei Pa inne maser (other than underscore) should be included in the identifier. real constants i . a 1S im exponent form : 17.251, 151.02, 0.00031, 00,452. We) 0.452 =0.0452 19! ' MOss2x1g! 5 = 0.0452 What is None tterad in Python ? " Solution. Python ha : The None literal is uy of value. It is 7 * I Salso used to indi that has indicate the eng of li not yet been created in simple words, or 13, pi AMON FUNDAMENTASS tr allowing Hterals ? sie ne of lt ; ve je Hoe True thd : False "Fale OXFACE = o213 00789 po g point a780 oating es 309 integer - i tan. Boolean | ‘True’ cine" rote Boolean False” String oxPAce Integer Hexadecimal) boat IntegertOctal ore invafd token (beginning with 0 means itis octal number but digits Bland 9 are invalid igi in octal numbers) None None erence betwen an expression aid a slatement in Python ? What i he | Solution. | hi Expression Statement Tegal combination of symbols Programming instructions per Python ayntax | j Represents something Does something | reevaluate tae caneth | | End sult isa value | ecu mot result in a value -raraple j Exams | 23 | print crierio® | B+y/4 | ifara: | (®) "This course is great!” (t) ‘She shouted "Hello!" very loudly." (0 “Goodbye” | (4) "This course 4s great!” ("Hello 12 Which ofthe following are syntactically correct strings? State reasons, () “Lliked the movie “Bruce Almighty’ very much." Solution. Strings (a), (8), (d) and (f) are syntactically correct. (Strings (b) and (f) are also valid as single ‘ote stings can use double-quotes inside them and vice versa.) String (¢) ( “Goodbye' ) is incorrect because opening and closing quotes don’t match. String () (“Hello) is invalid because it has no closing quotes. F i 3 What is the error in following Python programs with one statement ? Print ("My nane is", name) Suggest a solution. COMPUTER SCIENCE WITH PYTHON = iable name. The is trying to print the value of an undefined vari Soltion, The above SIE (fine the variable name before usin golution to above problem is to name «Tanya! print ("My name 4s", name) / is not giving desired output. We reant to inpul it vate as 20 and obtain output as 40. Could sing cote 4. The folowing: at ; goo pinpoint te problem ? . nunber = input ( "Enter Number" ) oubleTheNunber = Nusber * 2 Print (DoubleTheNunber) i tums value as Solution. The problem is that input) re! string ‘20° and not as integer 20. So the output is ot 40. Also Print( ) is not legal function of Python ; it should be print(). a string, so the input value 20 is returned as, 15, What would be the correetion for problems of previows question ? Solution, By using int{ ) with input( ), we can convert the string into integer value, ée., as : Nuaber = int (input (“Enter Number" ) ) DoubleTheNunber = Number * 2 print (DoubLeTheNumber) Now the program will print desired output as 40 if 20 is typed as input. 16. Why is following cade giving errors ? name = "Rehman" print ("Greetings | print (‘Hello", nane) print (‘How do you do 2") Solution. The problem with above code is inconsistent indentation. In P statement unless itis inside a suite and we can indent only ‘Thus, corrected code will be : ane = “Rehman” print ("Greetings 1! Print (‘Hello", name) Print ("How do you do 2") 'ython, we cannot indent a as much is required. Write int “Program locblain temperature in Celsius and com vert it into Falirenhe °Cx9/5432 07 “ it using formula i Solution, # Celsius to Fahrenheit 19. GL © Ide Ke Lex kt To! Str Va ex J PTHON FUNDAMENTALS = what will te the output produced by following code ? value =‘Simar’ age = 17 print (name, “, you are", 17, “now buts, end = ©) print (“you will be, 2 9B +4, “next year") solution. Shear, you are 17 now but you will be 18 next year, What will be the output of folloecing code ? B x y=2,6 Ks YRysxt+2 print (x, y) satuticn. 64 Explanation. First line of code assigns values 2 and 6 to va bles x and y respectively. Nex! line (second line) of code first evaluates right hand side i. Ye X42 which is 6,242 ic, 64; and then assigns this to, vise, x, ¥=6,4 60x gels 6 and y gels d, SS Third line prints x and y so the output is 6 4, 20. Prafict the output of follozving : xye7,2 K,YsX=x+1,y+3,x410 print (x, y) Solution. vs GLOSSARY _———— Constant A dala item that never changes its value during a program fun. Mester Nome given by user for a pait of the program Keyword Reserved word having special meaning and purpose. leet unt Other nome of token, Urerot Constant, , Toten The smallest individvol unit in a program (Rhaiterot Sequence of chorociers enclosed in any type of quotes. es Named stored location whose valve con be manipulated during program run. legal combination of symbols thot represents a value Type 1 2 Type What do you understand by block/code block/suite in Python ? nceptual Questions thon ? Examplify your answer, Questions/Co! a Ante types of tokens are allowed in Pyt A: Shor thon ? How many wre tokens in Py ahon " “ Sear eywwords different from identifier 1 mawatowid in Pyhon ? oo Is in Python ? How many types of literals a1 cansuet ee tors be used in Python ? How ? Give examples to support y' . aay veris represented in Python ? Give examples 10 support your answer. + are floating consta ; a + string literals represented and implemented in Phen 7 vo dei Wouch of these is not a legal numeric (ype in Python ? (a) int (b) floal Which of a i et for: ment of print() would you se 7 — net anevada separator (space) ? (i) printing the Following Fine in current lin eae ples of some unary and binary operators, What are operators ? What is their function ? Give examy {What is an expression and a statement ? What all components can a Python program contain ? What is the role of indentation in Python ? What are variables ? How are they important for a program ? What do you understand by undefined variable in Python ? What is Dynamic Typing feature of Python ? What would the following code do: X = ¥ What is the error in following code: X, Following variable definition is creating problem X = 0281 “Comments are useful and easy way to enhance readabi Elaborate with examples. find reasons. 'y and understandability of a program.” B : Application Based Questions fron te following, find out which assignment statement will produce an error. State reason(s) too, (a) x =85 (b) y =037 (6) = = 0098 vom : - («) 56thnumber = © length =450.17 (Taylor ="Instant’ (¢) this variable = 87.£02 meer (1) float =.17E-03 (i) FLOAT =0.178 — 03 . Find out the error(s) in following code fragments : (temperature = 99 (i) a=30 Print tenprature hzasb Wi) a,b, ¢=2, 8,9 print (a And 6) Print (a, b, c) tej basa, b, ¢ X= 24 4=x Print (ab; c) “© print cx 2rxy @) else=21_5 PYTHON FUNDAMENTALS be the output produced by following code frogment (5) 7 (i) fiestez #10 O pipet second =3 xex-5 third = first * second print (*) print (First, second, third) Xp ¥eX~ 2,22 first = first + second + third | print (X, ¥) ‘third = second * first | print (First, second, third) | ay sides int(input(‘side?)) Aside piven as7 areas side * side print (side, area) fs the problem with the following code fragments ? 4, What @ an3 | print (a) ba4 print (b) sea+b print (s) (i) pane = "Prejith” age = 26 print ("Your name & age are", name + age) (iy 223 | s=a+10 a= "New" qza/1e 5. Predict the output : e +1 8, y+ print (x, y) 6, Predict the output | x, Y= 28, 68 YX, Y=X, y- 10, xX+10 print (x, y) 7. Predict the output @ a, b=12, 13 () a, b=12, 13 ©, b=a*2, a/2 print (print(a+b)) Print (a, b, ¢) COMPUTER SCIENCE WITH PYTHON =) 8. Predict the output . 1b, c= 30, 20, 3 Pane (73, By C2748) Be cs ends “7 print (‘P,P ind the errors in following code frag Pea) ment (a= input ("value") 9. Fi b xey=5) ( yexes print (ney as iam prsae Cas) print (a, ) 10. Find the errors in following code fragment : (The input entered is XD = Int (input “Enter your class") ) print ("Your class is", ¢) 11, Consider the following code : name = input ("What is your name?") print (Hi', nane, ',") print ("How are you doing?") was intended to print outpul as Hi , How are you doing ? Bul itis printing the output as = Hi , How are you doing? What could be the problem ? Can you suggest the solution for the same 2 12. Find the errors in following code fragment : = input( “Enter your class" ) print ("Last year you were in class") c-1 13, What will be returned by Python as result of following statements? ® ) >>> type(a) (0) >>> type(int(a)) (6) >>>. type(int(‘@?)) (>>> type(‘e") (©) >>» type(1.¢) ‘ © : () >>> type(int(1.0)) > >type(float(@)) (hl) >>> type(float Match ‘oat (1.6) (i) >>> type( 3/2) ' ‘Your result after exccuting above statements, 4. VN vi a hat willbe the output produced by foll (a >>> str(print())+"One" 0) 99> str “hello iu (print “hello: ))+"One" ch Your result afi ‘ lor executing a 15. What will be the @ >> Sutput produced by followin, Print (print (“Hola”) 1B code ? © >> print print(etonae lowing code 2 bove statem, en's. Can you explain why this result came? end =)» NDAMENTALS" yereTHON FU 1, at the following code and fts execution on Python shell Why {s the last assigninient «carefully 120 ping err? pop an 012 poo prant(@) 10 jor b= 0013 po ¢# 0078 tinea pile “epython-input-41-27Fbe2fd265F>”, Line ¢= 0078 sgyntaxError : invalid syntax jt the output 7, Predict 4 a,b, ¢=2,3,4 a, by C= ata, arb, BC print(a, b, ¢) . . qe id{) can be used to get the memory address of a variable. Consider the following code and tell if the 4H TL) fancions will retumm the same value or not (as the value to be printed via print() )? Why ? [Ther are four print() function statements that are printing, id of variable mum below) num = 13 print( id(num) ) num = num+3 print( id(num) ) num = num = 3 print( id(num) ) nun = “Hello” print( id(num) ) 19, Consider below given two sets of codes, which are nearly identical, along with their execution in Python sives error, while second code-fragment does shell. Notice that first code-fragment after taking, inpul ? not produce error. Can you tell w (@) >>> print (num = float (input (“valuel:”)) ) valued :67 © ¢—A— nytt aera per execution of input() Traceback (most recent call last): File “”, line 1, in print(num = float (input (“valuel:”)) ) TypeErron: ‘num? is an invalid keyword argument for this function >> print (float (input(‘“valuel:”)) ) value1:67 67.8 + Code successfully exeetted. No error reported. a COMPUTER SCIENCE WITH PYTHON 20, Predict the output of the following code = days = int(input(""Tnput days? ")) * a 24 hours = int (input (“Input hours: ”)) minutes = int(input (“Input —_ i “ it secon seconds = int(input(““Inpu time = days + hours + minutes + seconds print(“The amounts of seconds”, time) If the input given is in this order : 1, 2, 3,4 Type C : Programming Practice/Knowledge based Questions el er es enter key. 4. Write a program that displays a joke. But display’ the punchline only when the user press . lint. may use input 2 bras popes to read ‘ata’ date (only del part) from user. Then display how man; the current month, 3, Write a program that generates the following output : 5 16 9 Assign value 5 to a variable using assignment operator (=) Multiply it with 2 to generate 10 and subtract 1 to generate 9. 4. Modify above program so as to print output as 50109, yy days are left in 5. Write the program with maximum three lines of code and that assigns first 5 multiples of a number to5 variables and then print them. 6 Write a Python program that accepts radius of a circle and prints its area. . Write Python program that accepls marks in 5 subjects and outputs aver: . Write ashort program that asks for your height in centimetres and ther inches, (I foot = 12 inches, 1 inch = 2.54 cm). . Write a program to read a number 10. Write a program to find area of a Write a program to compute simp! Write a program to iny age marks, n converts your height to feet and rand print 12, 0° and at, triangle. le interest and compound interest. Put a number and print its first five multiples. 'aine, class, age of a student and then print the details firstly in same Bae 18. Writ IMPORTAN Data Handling 3.4 Operators ‘a2. bata Types 25. Expressions 43, Mazabie and Immutable Types INTRODUCTION Inany language, there are some fundamentals you need to know before you can write even the most elementary programs. This chapter introduces some such fundamentals : data types, rarihles, operators and expr Python provides a predefined set of data types for handling the data it uses. Data can be stored inany of these data types. This chapter is going to discuss various types of data that you can store in Python. Of course, a program also needs a means to identify stored data, So, this chapter shall also talk about mutable and immutable variables in Python. sions in Python. In this chapter and onwards, we have shown screenshots of Python shell used in [Spyder IDE (Python shel) which uses In|]: prompt co take commands, But in text section, we tnd given commands with >>> prompt, which is a standard way of telling that this command is \ {ven on a Python shell prompt. | oe sels execute the code inthe same way, though [Python shell san enhanced shell, used choice but we lp (ea, Toronto University). You are free to use any Python IDE/shell of your \ i mae ave installed Python using Anaconda distribution which installs maximum | a eee SciPy, Panda and many more) along with Python. As Spyder IDE and oh scrensh available as part of Anaconda Python distribution and is very easy to use, we have ‘nshols of Spyder IDE and IPython shel! in this book at times. enclosed in 3.2. DATA TYPES real, string ele Anything end losed phe represents sting a and Trueand False repress vrtiraion pesent 3 ose © of may data. oot ee sre gps facies to handleall types of data. . a ma process different types 0! you can Before you eat em jueves various datatypes supported eles ont usa supped | SD in Python. In this discussion of data types, ¥ oe of ay vthon’s capabilities to handle a specific ye ioe, ae iielhe memory space it allocates to hold a __ 44 Serta type of data and the range of adata type etc. Python offers following built-in core data types (0) Dictionary. character, integer, = (@ Numbers (if) String (iii) List (iv) Tuple 3.2.1 Numbers ; - {As it is clear by the name the Number data types are used to store numeric values in Python, GHz» @ulntceereciened) _© Booleans 3.2.1A Integers GEE: 501917, 00. ese They have no fractional parts. Integers are represented : in Python by numeric values with no decimal point. * Integers (signed) Integers can be positive or negative, e.g., +12, - 15, 3000 * Booleans (missing + or- symbol means it is positive number), There are feo types of integers in Python : (0 tntegers (signed, 1tis the normal integer! representation of whole numbers, Integers in ba a gn o any length, it is only limited by the memory available, Unlike other t ng ‘62s, Python 3.x provides single data type (int) to store any integer, whether big or small. 'S signed representation, ic, the integers can be Positive as well as negative, (i) Booleans. These represent the truth v Bos values False and True. The Bool is i - The Boolean type is a subtype of Fe ileges, and Boolean values False and True behave like the values 0 ae 1 respectively equivalent of 0 or 1, you can type bool(0) or bool (1), Python will return False f values supported for a or True respectively, In Some cases, the exception Overflow i iunber oftyte, rror is raced instead if the given number cannot be represented throughia | weve Henin | sively The 5! e Shove (right side) 18 Fleoig Poin Numbers ‘A number havin integer. The mum Recall too forms : (Fractional Form (Ni | w@ {wat are the built-in core data types of 1 | ‘Python 2 | “2 What do you mean by Numeric types ? How many numeric data types does Fython provide ? 4 Mut will be the data types of following two variables ? A= 2147483647 BeA+1 (Hint. Carefully look the values they | axe storing. You can refer to range of | Prthon number table.) 4 iad are Boolean numbers ? Why are considered as a type of integers in Ryton ? " when you convert Boolean values Fatse and True the strings ‘False’ or True’ are returned, respec- fu{) function converts a value to string, See figure 1g fractional part is a Moating-p a ber. The decimal point signals th ting-point num! Pp igi Aoating ‘bor 12 is an integer, but 12.0 is a floating-point number. (from Literals/Values’ discussio Yormal Decimal Notation) ¢.g., 3500.75, 0.00005, 147.9101 etc. Exponent Notation e.g, 3.50075 (Out [30]: "True! joint number. For example, 3.14159 is a hat it is a floating-point number, not an chapter 2) that fractional numbers can be written in }, 0.5E-04, 1.479101E02 etc. Floating point variables represent real numbers, which are used for measurable quantities like distance, area, temperature etc. and typically have a fractional part. point numbers have itvo advantages over integers: Floatin; © They can represent values between the integers. © They can representa much greater range of values. But floating-point numbers suffer from one disadvantage also : © Floating-point operations are usually slower than integer operations. In Python, floating point numbers represent machine-level double precision floating point numbers? (15 digit precision), The range of these numbers is limited by underlying, machine archi- tecture subject to available (virtual) memory. tk ‘ per Python documentation, “Python does not support single-precision floating point numbers; the savings in processor ‘of using objects in Python, so there ea: the reason for using these is dwarfed by the overhead +0 eason to complicate the language with two kinds of floating point numbers”. EE ———— thon is a versatile language Camps Numbers? Hey, don’t you know about Com study about Complex mumters in class XI Mathematics arted, y bers, then for you to get started, | < Cnpler nates and then we shal ak aout Pylon’ representation ‘Mathematically, a complex number is a number of the form A+ 8i where i is the Imaginary number, : 4 equal to the square root of ~Xi.e, A complex number is made up of both real and imaginary components, In complex number A+Bi, A and B are real ‘numbers and jis imaginary. If we have a complex number z, where = ‘root represent the imaginary component of x, e.g., real component of +37is 4 and the imaginary component would be 3. Complex Numbers in Python number, Python uses j (or J) in place of traditional i, following examples where a and bate storing two complex numbers in Python : 43a b=1.S4 2a The above complex number a has real component as 0 and imaginary component as 3.1 ; in complex number b, the real 2 artis 15 and imaginary partis 2. When you display complex Python represents comple numbers, Python displays complex numbers in parentheses numbers as a pair of floating Point numbers, when they have a nonzero real part as shown in following examples. 29) = 044,57 >>>d=1.143.45 >> 4.53 aod (1,143.43) >>> print (c) ™ See, a comptes number with fom-zero weal pars is displayed wi 4.5; 3 puree aa >>> print (d) ut no paretheses aroun eon ae mite gaa compe COMPUTER SCIENCE WITH PYTHO} ii 3.2.1C Complex Numbers Complex Nunben a numeric type to represen! ipl 50, one about ples Faumbers? Uhh, Isee. You are Boing | book. Well, if you don’t know anything. 1am giving below bri Acomplex number is In the fc A4+BI where Hs the k Y number, equal to the square =a+bi then a would be the real component and & would of —1 be, J=3, tha Pe-1 Fython represents complex numbers in the form A+Bj. That is, to represent imaginary So in Python j= J/=1. Consider the introduction of of Complex numbers. Unlike Python's other i . numeric types, compk Parts : the real part imaging | Plex numbers are a i , et imaginary pert, both of veh ch ane ree made of two ‘mally as float values (floating point numbers), NOUNS gjpara na own gow can rt ‘a eal Bi 9 nimag Bi orexseples res the real part. | pora Gan ‘ por z.real * 3.0 poo z-imag, 7 4.0 [wat s1e floating point numbers ? hen are they preferred over integers 2 ‘2 that ae complex numbers ? How ‘nould Python represent a complex number with real part as 3 and inaginary part as - 2.5? Fiat wil be the output of following q=p+(1#1.5j) | print (p) print (q) | 4 wat wil be the cutput of following code? | r=2.54+3.95 j print (r.real) | print (r. imag) [5 Why does Python uses symbat j to i present imaginary part of a complex | tuber instead ofthe conventional f? | is Retr note above. n retrieve the two components using attribute references. For a complex number = 2°" ives the iuuginary part a5 a float, not as'a complex value.” pov z= (142.56}) + (4 -3.56§) : 1 wll pay rool par of comple unter 2 a Mw pay tmainary pt of ep mbes The range of numbers represented through Python's numeric data types is given below. ; ss i . + sacehs ton fa 'g es 1 separate character datatype, which most ‘other progiamiming Languages have’ that an hold a single “cation Joastrarts tank Tobie 31. the range of Python Numbers tx values True (1). False (0) an unlimited range, subject to available (virtual) memory on underlying machine Dawleons Floating point urbers architecture Same as floating point numbers because the real J imax inary parts are represented as floats. Complex 3.2.2 Strings You already know about strings (as data) in Python. In this section, we shall be talking about Python’s data type string, In Python 3.x, each character stored in a string? isa Unicode character. Or in other words, all strings in Python 3.x are Sequences of pure Unicnte chert ia ra-{oy saad Gaming, of ny Kon (ir ion gure set ‘unicode characters 34", S98’, 27277, “SAKA”, #727772", P27, “yy COMPUTER SCIENGE WITH PYTHON = can be individually accessed horacters TT Sng Sees of ten farce an ach ne i on st 1 Using its index. Let us Let us first study the internal structure oF comPO AT of all the learning of various string manipula! con one individual characters in contiguous: Tocation, wil ; characters con! individual elements of a string are the i reine ‘peations) and as mentioned the characters of a string are give! each location. Let us understand this with the help of an illustrat Figure 3.1. Structure of a Python String. sequence of under scion of Python strings asit will form the basis pis. Strings in Python are stored ag y index for each location. ained in it (stored in contiguous n two-way index for ‘ion as given in Fig. 3.1- From Fig. 3.1 you can infer that : ‘© Strings in Python are stored by storing each character separately in contiguous locations. © The characters of the strings are given two-way indices : = 0,1,2..... in the forward direction and = -1,-2,-3, ....in the backward direction, Gpserensmnacees any character asstrig RESIS) «cto acess the fist ch ig name shown in Fig, 3.1, you'll write namel0], because the 1 ris. You L, se the index of fis is saya witerame F-61for the above example i, when string name vesting "PY NeEN “ ‘us consider another string, say subject = ‘Computers’. It will be stored ae ‘ o 12 3 4 : : say name, of length In, the valh sri ing lke : ‘alld indices are, 1,2... Ine, That means, if you try to p> nase[1n) veill return an error like : qraceback (most recent cal} last): File “", line 1, in cmodules nare[In) indexError: string index out of range The reason is obvious that in string there the length of the string, thus accessing. causes an error. ‘Also, another thing that you must kno: is that you cannot change the individual letters of a string in place by assignment becau: and hence item assignment is not supported, é-c., is no index equal to an clement like this nane ="hello" individual letter assignment mn pane[O] ="8 4 alowed in ee thom tho will cause an error like : Traceback (most recent call last) File “cpyshell#3>", line 1, in >> print (a) (1, 2,354 5] st value in a list name’ wn above), you may write ly a (give em - consider statenent 1 ate, e To change fi change 1st it >>>.a [0] #10 >a [10, 2, 3,4 5] qoaangeceanionayenrey ert: © pp a(2]=30 # change 3rd item pa ght; the values internally are numbered from 0 (zero) onwards ic, fgg, ; l fits You guessed it ri ' : the list is internally numbered as 0, econd item of the list as 1, 3rd item as 2 and 59 9, "4 not going further in list discussion here. Lists shall be discussed in details ina later chaps Weare, 3.2.38 Tuples vou can think opkSpronounced as weppe. ayming wilh couple) Le as following are some tuples + 5 eo Tuples shall be discussed in details in a later chapter. 2.4. Dictionary Dictionary data type is another feature in Python’s hat following are some dictionaries : ; (851% 2,053,0 54, US) movowelse (at: 4,'e22,423,'024, Usp > ™ Me ; TL 0 and “ua 4, 3 are values for th the keys of dictionary vowels: se keys respect Sree he inside 11 after dictionary nan es he coms ponding value front the key : vatue poi inside dictionary Dictionaries shall be covered in det: ails in a later chapter. re summarizes the core data types of Python: _ ae ___—, ese — ==, =< a» regs com ome ote oe pont crepe 9 Following figu! Boolean 33 UTABLE AND IMMUTABLE TYPES ategorized into fey = uae and immutable types, i and non-modifiable types- ~The Python data objects can be broadly simple words changeable or modi 1 Immutoble types In Python, the following Inmate Tyra floating point numbers ms, stri : Bo ntegers, floating pint concept of immutable types. In low = types are immutabl Let us understand the order to understand this, consider the code bel Sample code 3.1 « gebpettans = = awillgives, 5,5 Pe10 re? qer + that values of integer variables p, q, 7 could be a can say | you may think that integer types can change rare integer type g the above code. After rea changed effortlessly. Since p values. But hold : It is not the ease. Let’s see how Jn, variable-names are just the references to value-objects i, You already know that in Pytho < do not store values themselves ic. they are not storage data values, The variable-name: containers. Recall section 2.5.1 where we briefly talked about it, en above. Internally, how Python processes these Now consider the Sample code 3.1 arefully go through figure 3.2 on the next page and then assignments is explained in Fig. 3.2. C. tead the following lines. So although it appears that the value of variable place” the fact is that the variable-names are instead made to refer to new object. (Changing in place means modifying the same value in same memory’ p/q/ ris changing ; values are nol changing “in immutable integer location). COMPUTER SCIENCE Wy Frio, “4 cecuted : tements are x these three stal © Initially # sabes having some vue reference the same value ee A abe a ference sae ge afc { gap bere ro res Figure 3.2 You can check/confirm it yourself using id( ). The id() returns the memory addrasiy which a variable is referencing. In [49]: p In 41}: a= p i Please note mate In (42): #25 22> are valid prompts of ‘Notice the 1a) 1s returning so ifferent Python shells. Wet, ‘samo memory addiess for in [43]: id(5) ‘value 5, p, q,1 = which In [] £15 2 prompt of ch et (a3]+ 2457662200 ‘means all these are Shell used with Spyder 17>) eferencing tho came object. is prompt of Python by IDLE IDE, ‘our captured screen text component we Please note, sessions, A memory addresses depend on your operating system and will vary indie © hen the next set of statements execute, ie P=10 Pez naer then these vari; viable nam, se | reap tersenctaenimarane mune | metas S214 5 will be the sane change, The original memory ad6r it i i rol * Same forother ase, ith the same value i, 5 bul P a Figure 3.3 In [49]: ger In [50]: id(10) lout{se}: 1457652288 tice, ths time with change la valve, the :aference memory address of variables pq and, rrhavo changed In [51]: id(p) out{s]: 1257662268 In [52]: id(7) : JOut(S2]: 1487662240 The valve 5 is atthe samo address tn [53]: idCa) lout [53]: 1457662220 In [54]: id(r) Jour [$4]: 1457662220 In [$5]: id(5) Jout(ss}: 1457662208 © Now if you assign 5 to any other variable. Let us see what happens "ow variable thos reference mamony 2d3t0ss same as inal roferonce memory ‘nddress of variable pwhen ithas value 5. Compare istings given above + id(t) = 1457662208 Thus, it is clear that variable names are stored as references fo a value-object. Each time you change the value, the variable’s reference memory address changes. - Variables (of certain types) are NOT LIKE storage containers ic, with fixed memory address where value changes every time. Hence they are IMMUTABLE. The objects of following value types are immutable in Python : © Integer © floating point number © Booleans © strings © tuples een SRIENCE YAN By re mutable in Python. These are: ind sels. ~ (a list, you M3) ists, dictionaries " write: To change a mentber chk = [24 6] chk(2] = 49 othe list namely Chk a8 [2- 40, 61. Je will mak chk = [2,4 6] ‘ Sos pen afer changing a value ia ro (63): oC) The ist Chk, us reference memory pee 35095936 <¢ ee) address has remained same. Thal In [62]: Chk[4] = 40 means ihe change has taken In place vthe lists aro mutable sacchk) A" + 150195536 Mutable objects are: dl jetlonory, set | Immutable objects: int, float, complex sing te Lists and Dictionaries shall be covered later in this book. 3.3.1 Variable Internals Python is an object oriented language. Python calls type of data as an object. An object is an entity that has cerlain properties and that exhibit a certain type of behavior, ¢ values are objects ~ they hold whole numbers only they have infinite precision (properties); they support all arithmetic operations (behavior). Saal ae or values are referred to as object in Python. similarly, we can say thata variable is al je aa twecan jeisalso an object that every entity that stores any values 0°27 Every Python object has three key attributes associated to it : easiness ince 4s ert >>> type (a) a celass ‘ine’ «————— seria Te of view aa i ine vane wi Currently refering 1a an incgecr valuc. Pai i chapiet 3 DATA HANDLING {i) The value of an object It is the data-item con ed in the object. For a literal, the value is the literal itself and for a variable the value is the data-i m it (the variable) is currently referencing. Using print statement you can display value of an object. For example, popaed 2. >>> print (a) vi pe Bil of rite as ats cent referencing inegor value 4 (ii) The id of an object The id of an object is generally the memory location of the object. Although id is implemen tation dependent but in most implementations it returns the memory location of the object. Built-in function id( ) returns the id of an object, eg., ao 4d(4) 30899122 « poasd 99> 4d (a) 30899132 ==> ~ 53 1. What is String data type in Python ? 2 What are two internal subtypes of String data in Python ? 3. How are sts type strings different from Unicode strings ? 4. What are List and Tuple data types of Python ? 5, How is 2 list type different from tuple data type of Python ? 6 What are Dictionaries in Python ? 2 Identify the types of data from the following set of data ‘Roshan’, Roshan’, False, ‘False’, ['R, ‘0','s', ‘t (R,'0','S'H, ‘a’, 8), (Rid, 22,1823," 4a 2M: 6}, (2.8-5), 12, 12.0, @.0, 6, 3j, 6+2.3j, True, "True" Mi ame us iit. Reval th 1 Pa ‘wd, | & What do you understand by mutable [and immutable objects ? ih nator a label ps Olvect 4 aremaliy sare a location s0sva052 The id() of a variable is same as the id() of value itis storing, Now consider this : Sample code 3.2 >>> ida) 1 30899132 then sare he emer tcaon of & masa issue a texan to kil ar 308 wo) able wis refering w. 30899132 222 = 5 *———— Variabe bis currently having nutue 5, ie >o> 4d(5) refering to integer wile 5 30899120 >>> id(b) 30899120 — Variable bil wow afer to tue 4 >>> be bed >>> id(b) 39899132 <—————_ Now notice that the id of wariable bis boo some asi of integer 4 “Ay SerP ‘Thus internal change in value of variable b (from 5 to 4) of sample code 3.2 will be representey as shown in Fig, 3.4. sosootaz bes 30899120 : ° oo b= bea wT Figure 3.4 Memory representation of sample code 3.2. Please note that while storing complex numbers, id’s are created differently, so a complex literal say 2.4j and a complex variable say x having value 2.4j may have different id's. DATA TYPES IN PYTHON, MUTABILITY, INTERNALS Progress In Python 3.1 In the Python Shell IDLE or {Python shell of Spyder IDE, type the statements as instructed. 1, Using value 12, create data-item (that contains 12 in it) of following types. Give at least to examples for each type of data, Check type of each of your examples using type ) function, eg, to check the type of 3.0, you can type on Python prompt type(3.0) (a) | Integer () | Floating point number (| Complex number Science with Python and fill i there in PriP 3.1 under Chapter 3 after proctically doing it on the computer. Please check the practical component-book — Progress in Computer » popiecce, hopter 3: DATA HANDLING 34 OPERATORS =. ‘The operations being carried out on data, are represented by operators. The symbols that trigget the operation faction on data, are called operators. The operations(specific tasks) are .d by Operators and the objects of the operation(s) are referred to as Operands, represente aes (i operators (iv) Logical operators (v) Bitwise operators (vf) Membership operators. Out of these, we shall talk about membership operators later when we talk about strings, lists, tuples and dictionaries. (Chapter 5 onwards) Let us discuss these operators in detail. 3.4.1 Arithmetic Operators To do arithmetic, Python uses arithmetic operators. Python provides operators for basic calculations, as given below : + addition Wt floor division - subtraction: % : multiplication ” exponenti | ! division Each of these operators is a binary operator ic, it requires two values (operands) to calculate a, final answer, Apart from these binary operators, Python provides two unary arithmetic operators (that require one operand) also, which are unary +, and unary ~. 3.4.1A Unary Operators Unary + The operators unary “+” precedes an operand. The operand (the value on which the operator yype and the result is the value of the operates) of the unary + operator must have arithmeti argument. For example, ifa=5 then +a means 5. ifa=0 then +a means 0. IUNARYIGRERATORS) ifa=-4 then +a@means -4. Unary - The operator unary - precedes an operand. The operand of the unary — operator must have arithmetic type and the result is the negation of its operand’s value. For example, ifa=5 then —a means —5. if a=0 then —a means 0 (there is no quantity known as — 0) ifa=-4 then-a means 4. ‘This operator reverses the sign of the operand’s value. . «Sina times these can be words too, ¢.g., in Python is and fs not are also operators. vas : eee . ators B P arn? ere act upon Wo operands are referred to as Operator orators. The operands of a binary operator are zi 2 shed as the left or right operand. Together the operator and its ‘operands constitute an expression 1, Addition operator + The arithmetic binary operator + yalues of its two: ‘operands. For exaniple, 4+20 results in 24 a+5 (where a= 2) resultsin 7 a+b(uherea=4,b=6) resultsin 16 For Addition operator + operands may be of number types’. Python also offers + as a concatenation operator wien used «with strings, lists and tuples, Ty functionality for sbrings will be covered in Chapter 3 ~ String Manipulation ; for list, it will covered in Chapter 7 — List Manipulation axlds values ofits operands and the result isthe sum of, 2. Subtraction operator - The — operator subtracts the second opers and from the first, For example, 14-3 evaluates to 11 a-b(wherea=7,b=5) evaluates to 2 x=3 (where x= ~1) evaluates to -4 ‘The operands may be of number types 3. Multiplication operator * ‘The * operator multiplies the v a°4 evaluates to 12 b*4 (where b=6) evaluates to 24 p*2(wherep= -5) evaluates to -10 a*c(whereg=3,c=5) evaluates to 15 alues of its operands. For example, The operands may be of integer or floating point member type Python also offers * as a replication operator when used with stri re 1 in Chapter 5 ~ String Manipulation. wen used with strings. This functionality will be oe 4. Division operator / The / operator in Python 3.x divides its first ope result asa float value, v.¢., st opecand by te second operand and alw. 4/2 evaluates to 2.8 100/10 evaluatesto 10.0 712.5 evaluatesto 2.8 100/32 evaluatesto 3,125 13.5/1.5 evaluatesto 9.9 Please note that in older version of Python (2.3), the / operator worked different! worke jerently. 5, ForBootean values Frue and False, recall that Python internal ia eau? oh nally takes values 1 and 0 (zero) respectively so True +1 wild copier 3 + DATA HANDUNG 5, Floor Division operaler // Python also offers another division operator //, which performs the floor division. The floor division is the division in w fractional part is truncated. a=15.9, b=3, o/b evaluates to 5.3. Now if you change the di ie, Ifo=15.9, b=3, o//b will evaluate to5.0 Consider some more examples : 190//32 evaluates to 3.0 7/13 evaluatesto 2 6.5/2 evaluntesto 3.0 ‘The operands may be of number types. 6. Modulus operator % The % operator finds the modulus (ic, remainder but pronounced as mo-du-lo) of its first operand relative to the second. That is, it produces the remainder of dividing the first operand by the second operand. For example, 19% 6 evaluates to, since 6 ors inte 19 three tines with a remainder 1. Similar! 7.2%3 will yield 2.2 6%2.5 will yield 2.0 The operands may be of munber types. Example 3.1 What the following cote 2 A,B, C,D=9.2, 2.0, 4, 21 print (A/4) print (A// 4) print (8 **C) print (0 //8) I he the output produced by print (A%C) Solution, 2.3 2.0 36.0 10.0 1.2 ich only the whole part of the result is given in the output and the To understand this, consider the third example of division given in division operator /, ie, vision operator /, with floor division operator // in above expression, Si the Fractional pur 0.5 is discon from the acta! result 3.5 ‘Floor division (//) trunce “fractional remainders and only the whole pata the result 7. Exponentiation operator The exponentiation _ operator ** performs exponentiation (power) calculation, ie. it returns the result of a number raised to a power (exponent). For example, 4 #7 Bevaluates to 64 (4?) o**b (a=7, b=4) evaluates to 2401 (a! i.e. 74). 0.5 (x=49.0) evaluates to 7.0. (x°5, tes, Vx, te., V99) 27,009 ** 0.3 evaluates to 2,68824413570761. (27.605°") The operands may be of number types. Example 3.2 Print the area ofa circle of radius 3.75 metres. Solution. Radius = 3.75 Area = 3.14159 * Radius ** 2 print (Area, 'sq. metre!) > COMPUTER SCIENCE WITH PYTHON _ adds values of its two operands. subtraction multiplication subtracts the value division Modulus (pro | mo-du-to) of Ra Mt | Floor division Exponentiation (Power) With the value of csult asa float value divides and truncates tht result, retums base raised to power exponent. (2.5? hen Negative Number Arithmetic in Python Arithmetic operations are straight(orw, non-division operators ic, -543 will giveyou 2 -5-3 willgiveyou -g -5°3 willgiveyou — -15 ~5983 willgiveyou 125 But when it comes to division and related operators (/, People get confused. Let us see how P understand this, we recommend that you look at the shown in the adjacent sercenshot and then look for its w sult is shown shaded explained below, where the ) -37 5 (-2 & 3)=5{-2 6 +2 (@) 4)=7{-2 @ 4)7(-2 -8 =3 —T +2 -47 (2 8 1 ard even with negative numbers, especially with 0), mostly hon evaluates: these. Ta Prteneweie Bi) cre | operation b In [67]: 5// -3 working oweterd: In [68]: -5 //3 © alas | ghia 3 aj 3 In [69): -7 7 4 3 Out[ea}: +1.75 e In (70): -7 4/4 Out[70}: -2 O -4 772 In (73): -7 54 out(72]: 1 In [72]: 7% -4 Out(72): «1 In (93): 7/7 + wilh chester 3 « DATA HANDUNG 34.1C Augmented Assignment Operatorsé You have learnt that Python has an assignment operator = RHS to the variablefobject on the LHS of Pyt operators, which combine the impact of an x if you want to add value of b to v; =a+b which assigns the value speci 1 value specified on hon also offers augmented assignment arilhes ic » arithmetic operator with an assignment operator, ‘tue of and assign the result toa, then instead of ea ing you may write ated Toad value of a 10 value of badd assign the result to b, you may write bia # instead of b= b+a operation | Description — ___ Comment xew Value of y subtra fx and then result assigned to x | Value of y multiplied to value of + and Her Fes | ! 7 | Value of y divides vatue of x and then result xexily [a computed and then result assigned to x of y divides value of a and the winder assigned tox These operators can be used anywhere that ordinary assignment is used. Augmented assignment doesn't violate mttobilily. Therefore, writing x= yereatesan enti ely new object x with the value x+y 3.4.2 Relational Operators An the term relational operaior, relational refers to the relationships that values (or operands) can have with one another. Thus, the relational operators determine the relation among different operands. Python provides six relational operators for comparing values (thus also called comparison operators) I the comparison is true, the relational expression results into the Boolean value True and to Boolean value False, if the comparison is false. The six relational operators are < less than, > greater than, less than oF equal to, equal to greater than or equal to, != not equal to, Relational operators work wil lists, tuples ete, h nearly all types of data in Python, such as numbers, strings, Relational operators work on following principles © For numeric types, the values are compared after removing trailing zeros after decimal Point from a floating point number. For example, 4 and 4.0 will be treated as equal (after removing trailing zeros from 4.0, it becomes equal to 4 only). ‘Mens note ts tle of combining assignment with other operator alo works with bitwise operators 1. What is the function of operators ? apeatar diferent fiom operator? 6 =" wélbretum true oe 3. What are binary operators ? Give God" < “Gedhouse” — will return True COMPUTER SCIENCE WITH Pri, Ml pared on the basis of lexicographical ordering (ordering in dictionary ‘Capital letters are considered lesser than small letters, ¢., ‘A’ is less than ‘a Yan tsagate pst ei Boks, i ical ordering is implemented via the corresponding codes or ordinat yay ‘AS ve tess than “a beeause ASCII value of letter ‘A’ (65) is less than ‘(87). You cn {for ordinal code of a character yourself using ord{c-2 see expression’ k 24, what will) corresponds to 1 Given that i= 4, be the result of following expressions ? (a+5) > (€-2) s+» expression 2 a ick (lic j (ii)icek W)i="J and not the following, ie dick (vi) j>k (vi) j>ai a+(5>¢)-2 +++ expression3 ‘wet Will) Jtei (in) j cok jon the expression 2 and not the expression 3. . | 2 What wt be the oiderof evaluation for Expression I means the exp =- { tome? -Though relational operators are easy to work with, yet while Ro? e5-6 (i) 010 Sa working with them, sometimes you get unexpected results ee pein wed behaviour from your program. To avoid so, I would LA orns two exriesint xe you to know certain ips regarding relational operators. \ stake sto use neasigmentoPerat only ps ena operator = rnalropeatoresns Do nt confuse resting te q with the assignment operator (=). For instance, the operator expression : valuel == 3 tests whether value? is equal to 3? The expression has the value True if the comparison is true otherwise it is False. But the expression valued = 3 assigns 3 to value] ; no comparison takes place. 3.4.3 Identity Operators There are two identity operators in Python is and is not. The identity operators are used 19 , the identity operators check if both the operands reference the same object memory é c compare the memory locations of two objects and return True or False accordingly. Operator | Usage Description is aisb returns True if both its 0 to same memory location), returns False otherwise. is not aisnoth | retums True if both its operands are pointing to different objects (ie,, both referring to different memory location), returns False otherwise. Consider the following examples : A=10 B=10 AisB will return True because both are referencing the memory address of value 10 You can use id() to confirm that both are referencing same memory address. lin (34): a = 235 In [35]: b = 240 ‘1s b reiurns False because a and b are relerring to different objects (235 and 240) als cretums True because botn a and ¢ are referring to same object (235) tn [36]: ¢ = 235 aisb False ise : True The Ids (10() )of a,b and c tellthat a and c ‘re referring to same object (their memory ‘Addresses are same) bul bis referring to a Giferent object as its memory address is ‘ferent from tha other two id(a), id(b), idfe: 80 49: print( i "4921240 nds are pointing to same object (i, both referring Chopter 3: DATA HANDLING Now if you change the value of b so that it is not rol ferring to same integer object, then expression ais b will return True : fin [48]: b= bs | Hin [41]: 9 is b Now b is also pointing a same integer Jout(42]: True ‘object(235) thus a is bs giving True this time, | ‘Their ids also reflect the samele,alla,b— ‘end ¢ aro refering Lo sare memory location | 1 [in [42]: print( id(a), id(b), id(e) ) {492124000 492122000 452124000 J rator. It returns Tre when both its operands are not The is not operator is opposite of the is ope referring to same memory address. 3.4.3A Equality (==) and Identity (is) — Important Relation You have seen in above given examples that whe is operator returns True. When the means that the equality operator will that n two variables are referring tosame value, the is operator returns True for two variables, it implicitly also return True. That is, expression a is b as True means will also be True, always. See below print (a, b ) But itis not always true other way round. That means there are some cases where you will find that the two objects are having just the same valu is operator returns False. operator returns True for them but the See in the screenshots shown here. iEn [48]: 52 abe Hn [46]: 52 = input("Enter 9 steing iEnter a stringsabe » The stings $1 and s2 although have the same value ‘abe’ in them 1 True * Tho == operator also returns True for s1 == 82. | 31 is s2 sis * But the Is operator returns False for st Is 52 Lis s3 True COMPUTER SCIENCE WITH PION J : ‘ejects Fand store the same complex number value 243.5 im them ut fs oporator returns False i tn ($4) fan (52): 3 = 20959 for t1sJ 9 (sa): bis an tsa}: i 3 Also, a gn ter a valves") = float (input(“é ite [58]# i jabios k and / both store float value 3.5 5 and | has taken this = The vari (Khas been assigned 3. value through input() and float) ) «Bulk == reums True and k is I returns False lentes a value:3.5 fan (56): ke 1 lovtse]: True fan (s7]: k is 2 ‘outTs?]: False The reason behind this behaviour is that there are a few cases where Python creates two different objects that both store the same value. These are : f © input of strings from the console; © writing integers literals with many digits (very big integers); © writing floating-point and complex literals, Following figure illustrates one of the above given screenshots, Hn [46]: 52 = imput(“toter 9 st ) stringsabe Js st se 52 2 True sis 32 jOut(48): False We just need to ch ol ‘ ' ame valueor not fan hether the two W the 1s operator ret | Fo ths teat chee CASE he equality FO" wo objects then th i ; . However, j t 5 then th ree ants OF in your projects, you maytined in advanced eperator must eeu Te ey refer to same mem ced to check whether Sime objects, re, | ory address or no} ‘an use the is operator, t — in this case, you che 3.4 v= jen 32 DATA HANDLING Logical Operators earlier section discussed about relational operators t i pmo en le chorea operators hat establish relationships among the pat refer to the ways these relationships (among values) can be conneeted, Python provides three logical operators to combine existing expressions, These are or, and, and not Before we proceed to the discussion of logical operators, itis important for you to know about Truth Value Testing, because in some cases logical operators base their results on truth value testing 34.44 Truth Value Testing Python associates with every value type, some truth value (the truthiness), i, Python internally categorizes them as true or false, Any object can be tested for truth value, Python considers following values false, (ie., with truth-value as false) and true : 34.4 Values with truth value as false Values with truth value as true None Take (Boolean value False) zero of any numeric type, for example, 0, 0, Oj Ail'othar valves are 1 considered tru. empty string ;() is empty tuple and [] is empty list) any empty sequence, for examp! {please note,” any emply mapping, for example, { | Tre result of a relational expression can be True or False depending upon the values of its operands and the comparison taking place. | Do not confuse between Boolean values True, False and truth values (truthiness values) true, | fats. Simply put truth-value tests for zero-ness or emptiness of a value. Boolean values belong tojust one data type, ie, Boolean type, wher an test truthiness for every value object in. Python. But to avoid any confusion, we shall be giving truth values fru and false in small letters th a subscript ful, ie., now on in this chapter tme,,.) and false,,.; will be referring to truth-values of an object. 3M The utility of Truth Value testing will be clear to you as we are discussing the functioning of logical operators, u 44B The or Operator The or operator combines {110 expressions, 'ese ways : which make ils operands. The or operator works in © relational expressions as operands (ii) numbers or strings or lists as operands {) Relational expressions os operands or operator has its operands as relational expressions (¢8., > q-j =k, ete) then the or °Perator performs as per following principle : The or operator evaluates to True if either of its (relational) operands evaluates to Twue ; Faise if both operands evaluate to False. the Boolean logical operators (or, and, not) | JOMPUTER SCIENCE WITH PYTHON ce % y pe False False False True True True False True True True True Following are some examples of this er operation + results into True because first expression (4 expressions 5 > 8 and 5 <2 are False, }) is True. (4==4) or (5==8) 5>e0rs<2 results into False because both (i) Numbers / strings / lists 08 operands? When or operator has its operands as numbers or strings or lists (c. the or operator performs as per following principle , ‘a’ or”, 3 00, etc.) then In an expression x or y, if first operand, (ie., expression x) has false,,... then return second operand y as result, otherwise return x, That is ' ¥ xory : aq falseny fey : 7 ‘in general, True and Fal fue : represent the Boolean Mere . and true and false repr tu mesh : ruth values. Examples Operation | Results into Ss 2 : Reason 7 : Test xpresion 0) as false, hence second expression 0b wma “0 ion 0 is retumed pes 5 fest capresion (0) has fasta hence second eapresion 8 is ey “ : ms ° ression 8 is relumed, est expression (5) has true, honee fi el ‘ve hence first expression § is retumed. mae first expression (hells) has trey, hone fst expression ‘ell * . oem ssion ‘hello is rtumedt ore ‘ Preston (hase y ence securd expression ai ed rst expression (*) has a an . C7 M8 flea ence second expression * ert ed etumed, first expressi sion (‘a') as trey, hence fi ra hence first expression ‘a ion ‘a’ is returned, How the truth value 4s determined 2 ~ Pr to section 3.4.4 above. ai |: DATA HANDLING 5 or operator will test the second operand only if the first operand i is its Ten ine second operand is logically wrong eg, SS ans fle ator Boe 7 yo>1or*a" +191 i a Mute | | | atigive you result as | true without chocking the second operand of or ic, “a” 41> 1, which is syntactically wrong — you cannot add an integer to a string aac The and Operator The and operator combines fwvo expressions, which make its operands. The and operator works in these ways t () relational expressions as operands {i) numbers or strings or lists as operands {Relational expressions os operands When and operator has its operands as relational expressions (¢.¢..P> 4. operator performs as per following principle : i, etc.) then the and The and operator evaluates to True if both of its (relational) operands evaluate to True ; False if either or both operands evaluate to False. That ! x y xandy False False False False True False True False False ‘True True True Following are some examples of the and operation : ( 4) is True but second expression 4) and (S == 8) results into False because first expression (4 (5 == 8) evaluates to False. Both operands have to result into Trac in order to have the final results as True i 5>8 and S<2 resulls into False because first expression : 5 > B evaluates to False. B>5and2 <5 results inlo True because both operands : 8> Sand 2.<5 evaluate to True (i) Numbers / strings / lists os operonds® When and operator has its operands as numbers or strings or lists (¢g. ‘a or”, 3 or 0, etc.) then and operator performs as per following principle : Inn expression x and y, if first operand, (ie.. expression x) has false, then return fitst operand x as result, otherwise return y. COMPUTER SCIENCE WITH PYTHON, y false i 7 (skew - | tri t “ false pet tren ” irene true! | Berle | Reason ——— a opesioe | aesisinie (Oy has fase bene fst expression 0 is Fel ] Fat expression (0) has fos ec ae | ; ee (oasis Hees Fist eNRESSE n O is re naa cest expression (0) 138 fly Sadie aoa H ; 7 vreson() try ence second eNPrES ns aed + ae es «renew second expression “is retuned " =| fit expression (hells) has IM ear "i ae . fist expression (°) fas fist ence frst expression 18 returned. me | inte expression “is retumed. and" . fis expression (") has fly hence frst expre is roa i + hence second expression ‘is retumed, andy | fist expression (at) has trite gp hence How the truth value is determined ? ~ refer to section 3.4.44 above. foe th “IMPORTANT é ‘The and operator will test the second oper it; even if the second operand is logicall 16> 20and"9"4 10.5. will give you resull as ind operator will test the False second operand only If the ignoring the second operand completely, even ifitiswrong- Gherand tues othe you cannot add an integer to a string in Python. 3.4.4D The not Operator The Boolean/logical not operator, operator. The logical not operato: following ite, ifthe ind only if the first operand is trie, otherwise ignore wrong es works on single expression or operand ie., it is a unary | ot opera or negates or reverses the truth value of the expression Pression is True or true 4p , then nol expression is False, and vice verse: Unlike‘and’ and ‘or’ operators that can tring ora list etc. as result, the ‘no!’ retum ‘operator retums ala umber or a 8 a Boolean value True or False. Consider some examples below : nots resul ee results into False because 5 is non-zero fie, trey) nr Tesults into Trae because 0 is zero (ie., false, ) . results into False deca fe 7 me because —4 is non zet0 thus trey) not(S > 9) ore ry on sa. at’ pATA HANDLING slowing table summarizes the logical operators Ee | fol me Logical Operators 34 is Result Notes Ff is false, then re my | It (or) only evaluaie ita Ge falsen OMY €alustes the second argument the fiat one a iC is fale then x as u {and) only evaluates the second argument if the frat one fy resul, ese v en m ifr is false, then return | not has Truc as result, else False @ lower priority than non-Boolean operators. Gained Comparison Operators While discussing Logical operators, Python has somet multiple comparisons which are like shorte how. Rather than writing 1 <2 and 2< ofeatlier Boolean expression. ‘hing, interesting to offer. You can chain ‘ned version of larger Boolean expressions. Let us sec 3. you can even write 1<2 <3, which the ch id version The above statement will check if 1 teas fess than 2 and if2 was less than 3 Let's look at a few examples of using chains : pov e263 isequivalent to »9>1¢2and2<3 True True Asperthe property of and, the expression 1.<3 will be first evaluated and if only it is True, then. only the next chained expression 2 <3 will be evaluated Similarly consider some more es don 13912 True The above expression checks if 13 is larger than both the other numbers ; it is the shortened version of 11.< 13 and 13 > 12. 345 Bitwise Operators Python also provides another category of operators - bitwise operators, which are similar to the logical operators, except that they’ work on a smaller scale ~ on binary representations of data. Uibwvise operators are used to change individual bits in an operand. Fython provides following bitwise operators Ti835 sitwise operators tera Description | {1D oper pares two bits and generates a result of 1 if 31 & op? | The AND operator compare 5 OPS OPE oth bis ane I lherwse i chums 0, Sitwise or ops | op2 | The OR operator compares two bi bits are complementary; otherw' opt * 1e EXCLUSIVE-OR (XOR) operator compares two bits and returns PL 0p? | Ta ther of the bits ave 1 ad it gives O if both bits are 0 or 1. ~opi ‘The COMPLEMENT operator is used to invert all of the bits of the bitwise and and generates a result of 1 if the , it retuns D. bitwise sor operand COMPUTER SCIENCE WITH PYTHON, Let us examine them one by one. ¢ bitwise AND function on, 3.4.50 The Al th c jon performs tir g the resulting bit to 1 if ND operator & fe rat ands are numbers tne & OPS nd, The AND function 5 erand. rs ving Table 3.6. ipa fis i coc @petan ETT yf the folowing 7 parallel Ping bit in bath operands is 1 a5 corresponding | Toute 36 ‘The Bitwise AND (&) Operation ; opa Result , i t 9 a For AND operations, 1 AND 1 pro luces 1, i s 0. D 1 0 ‘Any other combination produce: j 1 ° 0 * * * In [76]: bin(13) 13612 1101 tr , Suppose that you were to AND the values 13 out [76]: "eb1161 and 12, like 3 & 12. The result of this operation is 12 because the binary representation of 12 is 1100, and the bina representation of 13 is 1101. You can use bin() to get binary representation of a number. If both operand bits are 1, the AND function sels the resulting bit to 1; otherwise, the | resulting bit is 0. So, when you line up the two —J operands and perform the AND function, you can see that the igh-order bits (the twe farthest to the left of each number) of each operand Se The ere a ihe wo also 1. The low-order bits evaluate tod because ei in [77]: bin(12) | out[77]: '@b1200" | | | t } in [78]; 13 & 12 j Out[78]: 12 | { | 1 In [79] out(79. bin(13 & 12) *“@b110% 7 Thus, the resulting bit in the resultis ither one or both bits in the operands are 0. 3.4.58 The inclusive OR operator | When both of its operands are numb werands are numbers, the | operator performs Inclusive OR means that if vither of the twe bite ie isthe real | “ shows the results of inclusive OR operations, ‘ ji ‘the inclusive OR operation result is 1. The following Table 37, Table 3.7. the inctsive OR (|) Operation bin(13) ‘eb1101° 13/12 e900 21901 009 1109 bin(12) ‘@b11¢60" bin(13 | 12)| *@b1101" 2 ORO prod Any other Combination Wishart r i i | | | t { { i | | 1 | | | | | | 1 u 3.4

You might also like