Sei sulla pagina 1di 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 421 - 182 183 - 209 M25 3A Logical Operators 91 345 Bitwise Operators 95 34.6 Operator Precedence 97 35 Expressions 35.1 Lealuating Expressions 101 352. Type Casting 105 CONDITIONAL AND ITERATIVE STATEMENTS 4.1 Introduction 4.2. 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. The ifStatements of Python 454 The if Statement 129 452° The if-else Statement 131 453° The if-elif Slatement 136 4544 The nested if Statement 138 4.6. Repetition of Tasks ~a Necessity 4.7 Therange() 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 16 Nested Leep STRING MANIPULATION 5.1 Introduction 5.2. Traversinga String 5.3. String Operators 53.1 Basic Operators 1 5.3.2 Membership Operators 185 5.33. Comparison Operators. 189 SA String Slices 55. String Functions and Methods DEBUGGING PROGRAMS 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 a, 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 Dio pAWWw.worldvideweb.co 307-322, 101 Introduction is 307 102 Whats Sorting? aoe 103 BubbleSort oe “! 104 Insertion Sort a8 11 States AND TraNsitIONs 323-332 1.1 Introduction be 11.2 Magical island ~the Island of Victory - 113 States, Transitions and Diagrams ae 12 COMPUTER System Overview 333-354 122 Introduction a 12.2. Basic Computer Organization 334 12.21 Input Unit 334 Output Unit 235 The CPU (Central Provessing Unit) 335 ‘The Memory {Main Memory/Prinary Memory! 336 The Storage Unit 439 The System Bus 342 12.3. Mobile System Organization 342 124. Types of Software 348 TLAT System Software 385 124.2 Application Softiome 346 T2AS Software Libraries 343 13 DATA REPRESENTATION 355-384 13.1 Introduction 355 13.2. Digital Number Systems 356 13.21 Decimal Nunber System 350 13.22 Binary Number System: 350 13.23 Octal Number Systeve 3) 1324 Heratecinal Number System 358 13.3, Number Conversions 133.1 Decimal-to-Binary Convers 133.2. Binary-to-Decimel Conversion 362 13.3.3 Decimal-to-Octal Conversion 363 1334 Octal-fo-Decimal Conversion 363 1335 Octal-to-Dinary Conversion 363 13.3.6 Binary-to-Octal Conversion 364 13.3.7 Decimal-to Hex Conversion 364 13.38 Hex-to-Decimal Conversion 365 133.9 Binary-to-Hex Conversion 365 133.10 Hex fo Binary Conversion 365 134. Representing Unsigned Integers in Binary 367 135. Binary Addition 368 Ye | al 359 -aeer/string Representation pBE Myaaascit Cale 371 p62 1sCll Cale 37? 163 Uniowe 373 TF Boouean LOGIC 141. Developmentof 395 - 424 | 142. Binary Valued Quant } { ‘Boolean Logic ities ] ions 3 Logical Operation: i" Nad esi Function or Cervud Stoterent 386 i 1432. Lagical Operators sr 1433. Eeuluation of Boolean Exp 89) | 393 | wressions Using Truth Table 3 144 Basic Logic Gates TAL Inverter (NOT Gate) 393 Haz OK Gate 35 ! 1443 AND sate 394 | 145. Basic Postulates of Boolean Logie 395 14.6 Principle of Duality 395 147. Basic Theorems of Boolean Algebra/Logic 396 14z.1 Properties of O and 1 398 1472. Inderpotence Law 5397 1473. Irsetution 397 N74) Complementarity Law 528 1475. Commutative Les ! 176 Associative Lane 359 M477 Distributice Law 40 475 Absorption Laws 40 179. Some Other Rules of Botean Legie Algebra 4 148. DeMorgan's Theorems BL DeMorgen’s Fist Theorem 4002 182 DeMorgan’s Second Theorem 403 149. Simplifying Boolean Expression M91 Algetnaic Methal 0 14.10 More About Logic Gates “or 14.101 NOR Gate 407 | 1 | | | 402 4050 14.102 NAND Gale $07 14.103 XOR Gate (Exclusire OR Gate) 08 4104 XNOR Gate (Exclusive NOR gate) 109 105 NAND to NAND and NOR to NOR design 410 15 INSIGHT INTO PROGRAM EXECUTION 425-440 151 Introduction 32 Basic Flow of Compilation Understanding Translation Process 153.1 The Compilation Process 426 tse ee inert Pres 19 \ 12 Role of an Operating System in Running a Program = Nww.worldvideweb.com 185. Introduction to Parallel Computing 15.6 Cloud Computing 16 RELATIONAL DATABASES 161 Introduction _ 162 Purpose of DBMS 163. Relational Database Model E 164 The Relational Mode! Terminology T641 Views 447 164.2 Structure of Retational Databases 447 165 Brief History of MySQL 16.6 MySQL Database System 167 Starting MySQL 168 MySQLand sql. 168.1 Procissing Capabilities of SQL 452 1682 Data Definition Language 453 1683 Clossification of SQL Staterients 454 17 ii SIMPLE QUERIES IN SQL 459 - 498 | 17.1 INTRODUCTION | 17.2, Some MySQL SQL Elements. | 172.1 Literals 40 | 1722 Data Types 460 | 1723 les 463 W724 Comments 463 SQL. Command Syntax Sample Database Making Simple Queries TES1 Accessing Database $67 W752 The SELECT Command 467 17.53 Selecting all Columns jos 1754 Reordering Columns in Query Results 46 17.55 — Eliminating Redundant Ds DISTINCT) 468 175.6 Selecting from all the Rows = ALL Keyword 469 175.7 Viewing Structure of Table 470 175.8 How to Perform Siniple Caleulations ? 470. 17.5.9 Scalar Expressions with Selected Fields 471 17.58.10 Using Colur Miases 47 175.11 Handling Nulls 473 175.12 Putting Test in the Query Output 474 Selecting Specific Rows - WHERE clause 476 Relational Operators 476 Logical Operators 477 Condition Based on a Range 478 Condition Based on a List 473 Condition Based on Pattern Matches 479 Searching for NULL 481 with heya 436 437 441 442 4az MAS 449 450 451 452 459 460 463 464 467 preceience 181 nso opera POT ORDER BY ehise 492 rat Sorting Rol 16 Mysqu Functions 176 Med sirms Functions 48 % a z CREATION AND DATA MANIPULATION COMMANDS BLE 18 16.1 Introduction Databases in MysQl 182.1, Creating Databases 12 os 30 wees 183 Creating Tables 184 Changing Data with DML Commands 1 i ge DILETE Coen 51 18.5 More DDL Commands mtg rus Come! 5 162 tabases 500 ugh Constraints 501 527 550 19.1 Introduction 527 19.2 Joins 527 1921 Using Table linses 531 19.22. Additional Search Conditions in Joins 532 19.23 Joining More Than Two Tables 533 19.24 Equi join 534 19.25. Now-Equi-foins 534 19.26 Natural Join 534 193. Indexesin Database 193.1 Crovling Indexes in MySQL 540 ” 19 i ‘TABLE JOINS AND INDEXES IN SQL bs 20! Basics oF ~ NOSQL DATABASE - MONGODB 551-584 20. Introduction 202 Whatare NoSQL databases ? = me : Ts af NOSQL Databases 553 “ vantages and Dis i tl Disudoantages of Ne (al 5 i Dovroatingand stain Morgans ne Working With MongoDB = a 2 MorgoDB Terminology 559 mie Starting MongoDB Service 560) 43 MongeDB Basic Commands 560 559 205 CRUD Operations in MongoDB 205.1 Creste Operation 562 2052 Real Operatans 566 2053. Some Basic Operators 571 2054 Upsate Operation 576 2055. Delete Operation $73 J Cyber SAFETY 21.1 Introduction 585-598 21.2 Whatis Cyber Safety? 21.3. Safely Browsing The Web 21.4 Identity Protection While Using Internet 214.4 Many Woys Websites Teack you 586 2442. Priate Browsing and Auonymous Broesing 588 21.5 Confidentiality of Information 2151 Practices to Ensure Confentiatity of Information 589 216 Cybercrime 2161 Reporting Cybercrime 21.7 Common Social Networking Sites 21.8 Appropriate Usage of Social Networks 2181 $Wint You Should Know ? 593 218.2 Wiat You skoutd do Usage Rules 394 22 | ONLINE Access AND COMPUTER SECURITY 22.1 Introduction 22.2 Threatsto Computer Security 1 Computer Viruses 600) 599 - 610 spyinre 600 Adware 602 3 4 Spamming 601 5 PC Intrusion 62 6 Eavesdropping 6 Phishin 8 Cookies 603 223. Solutions to Computer Security Threats 22.3.1 Solutions to Virnses, Adware and Spyware 604 22.3.2. Solutions to Spam, Eavesdropping 605 22.3.3. Solutions to PC [utrusion ole 2234 Solutions to Phishing and Pharming Attack 606 224. Firowall- An Important Solution for Computer Security on and Pharn 2. APPENDIX 611 - 624 Appendix: Installing Python Appendix B: Arguments to print Function Appendix C; Installing MongoDB Appendix D: Formatted Output using String format() a- 562 58S SBS S86 586 588 5oL 593 593 599 599 603 607 611 618 619 623 Getting Started with Python a ty Mis Cheater 11 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 programming language was developed by Guido Van Rossum in February 1991. Python is based on or influenced with fivo programming languages : © ABC language, a teaching language created as a replacement of BASIC, and © Mottta-3 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 © gis ne 21 www.worldvideweb.com Python a Fundamentals © | di \ 2.1 Introduction 2.2 Python Character Set 23. Tokens Barebones o! a Python Program 2.5. Variables and Assignments. 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. 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, {this chapter, we shall be talking about all basic elements that a Python program can contain. You'll be leaming about Python's basics like character st, tokens, expressions, clalements, simple to take our first sincere step towards Python Programming ? And, here we go >). (put. Most (in fact, nearly all) daily life is, there is certain Input, certain kind of input and output etc. So, are we all ready COMPUTER SCIENCE WITH PITHON n HARACTER SET | 2.2 PYTHON Cl is a set of valid characters that a language can recognize. A character i Character st 8246 other symbol. Python supports Unicode encoding standard, Thee ean y letter, i : Pie has the following character set : © Letters A-2, a-z © Digits “ se ‘al sy' space +-*/**\()(]{}// e lean six © Special symbols &# <= >= @_(underscore) © Whitespaces Blank space, tabs (-»), carriage return (-!), newline, fornfeeg, © Other characters Python can process al ASCIT and Unicode characters as part of data or literals. 2.3 TOKENS Ina passage of fext, individual words and punctuation marks are called fokerts or lexical units op Jexical elements. The smallest individual unit in a program is known as.a Token ora lexical unit, Python has following tokens : Keywords (ii) Ident The smallest individual unit ina roptam is known a a Token o era D) ‘tuators: Program is (f) Operators (v) Punctuator a lexical unt. iers (Names) (iii) Literals Let us talk about these one by one. 2.3.1 Keywords Keywords are the words that conv pecial meaning to the language compiler/interpreter. These are reserved for special A seen toe re ant Purpose and must not be used as normal identifier names programming language Python programming language conlains the following keywords : False assert del for in or while None break elif from is pass with True class el global lambda rais yield and continue except if nonlocal return as def finally import not uy 2.3.2. Identifiers (Names) Identifiers are fundamental building blocks of a lerminology for the names given to diff erent parts of the program viz. variables, objects, classes, functions, lists, dictionaries etc, Tdentifier forming rules of Python are being specified below : ! © An identifier is an arbitrarily tong sequen © The first character must be a letter; the w ce of letters and digits. inderscore (_) counts as a letter, 2: PYTHON FUNDAMENTALS © Upper and lowercase letters are different, All characters are significant. © The digits 0 through 9 can be part of the identifier except for the first character. © Identifi fs are unlimited in length, Case is significant i.e, Python is case sensitive as it treats upper and lower-case characters differently. © An identifier must not be a keyword of © An identifier cannot contain any 'ython. special character except for underscore (_) The following are some valid identifiers : byfile DATES_7_77—22T@79 MVFILE DS -HI13_IK aoHK FILE13 The following are some jnvalid identifiers : DATA-REC contains special character (hyphen) (other thon A - Z, a+ z and _ (underscore) ) 29cLcT g with a digit break My.file S speesal 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 (1) Boolean 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 ; e many other Ia . both single character enclosed in quotes such as “a” or x’ of multiple characters | 1 What is meant by token ? Name the enclosed in quotes such as “abe” or ‘xyz’ are treated as tokens available in Python. String literals. 2 What ate keywords ? Can keywords be As you can notice, one can form string literals by enclosing wed as identifiers ? text in both forms of quotes - single quotes or double 3. What 1s an identifier ? What are the ji quotes. Following are some valid string literals in Python : identifier forming rules of Python ? - 4. Is Python case sensitive ? What is ‘astha’ “Rizwan” | __ meant by the term ‘case sensitive’ ? HelloWorld = “Any’s" S Which of the following ate valid "129045" Wdentifiers and why/why not = "Lex-0-w-25" | Dataree, data, 1 data, datat, my.file, -332F60291" | Alb 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 eseangonwet on cesed) stri=""Hello world. There ICome IL Cheers. tenis Tore 7 Covell! rors ° roase note ts singlo #9 ‘ore munive stra aol Or tae tryteteay 6 Prrmcrn _ str2="* "Hello Size of Strings COMPUTER SCIENCE WITH PITHO,, imckslash so marks. (No bck axt in tripe quota type multilin (By typing Ie tale on ae *eotation marks nec enclosing them in (iP lon Mm work), aks will ple For example, aia nirgaested ah tbvee single HOES world. This is another multiline string. in [a]: prine(ste2) Nelle Worle This is another multiline string. Tule sting created with thie singie quotes {opening and closing) nol: Python determines the size of a string as th¢ count of ch string “cbc” is 3 and of ‘ tonal within it, then make sur examples given below ay lites eal ; in the string. For example, size of cy 5. But if your string literal has an escape sequence contzined count the escape sequence as one character. Consider some eS seis | (\\is an escape sequence to represent backslash) size is 3 : "\ab* i hee = is 2 (\is an escape sequence, thus one character). is i ‘tay (For typing apostrophe () sign, escape sequence \' has been used). si : ize is 4 Python allows a single Aouble-quoted string a oie thot escape sequence) in ind vice-versa, 4 cuoewe 2 FUTON FUNDAMENTALS For multiline striny character at the end 0 ng SE stra* bue oe then size of the string Str3 characters @ and PF respectiv For multiline strings created Hine, while calculating size, cannot put EOLs using, ret stra ='a\ by pn ‘The size of string Str4 is 3 (only 3 characters, To check the size of a string command on the P3 shown in the following figur [eter -eorrten wort I wer ge created with triple quol fie line ds also courted i 9x byrecrnie By crwen Tn [2]: Std =e sents" LOL (end-of-line) created a while calculating, size the size, For example, two EOL characters that follow is 5 (three characters @, b, ¢ and th single/double quotes and backslash character at end of the ove nat counted in the size of the string ; also you the backslash 1 key in single/double quoted multiline strings 68 — | no backslash counted.) you may also type len() Use lenfcobject name>) 10 get hon prompt in console window shell as the size or Fength of an object. — ox a Triple quoted multine stings also count EOL charactors in the size of the sting. Single!couble quoted strings typed in multiple line with \ at the end of each intermediate line do not count \ in the size of the string en(str3) outhay: 5 In [4]: len(Stes out (a): 3 = 1 (5): | Triple quoted multiline strings ‘count EOL characters in the 2.3.38 Numeric Literals The numeric literals in Pythor int Gigned integers) lat (Noating point real values) complex (complex numbers) eo (rd-c-ines CRU Encoding UTES of the string but do not cou vine 5 backslashes ( \) at the end of ‘intermediate lines, a Vee 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 re b id are written with a decimal poi re al numbers and are write decit t s represe s a wi dividing the integer and fractional parts. ta ene? Ok where @ and b are floats and J (or j ) represents 5 an imag er). ais sare ean nag ary ui). 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 fa. hat are Uterals ? How many types of 1 tterats ae available in Python ? | 2. How many types of integer literals are allowed in Python ? How are they written ? 3. Why are characters \, ‘, ” and tab typed. using escape sequences 7 4, Which escape sequences represent the newline character and backspace character? AN escape sequence represents how many characters ? 5. What are string-literals in Python ? How many ways, can you create String 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 ? 7. Write the following real constants into ‘exponent form : 23.197, 7.214, 0.00005, 0.319 8. Write the following real constants into fractional form = 0.13E04, 0.417E-04, 0.4E-5, 12602, 12.602 9. What are the two Boolean literals in Python 2 40, Hame 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 form or string literal or other ? 123, 00124, OxABC, ‘abe’, “ABC", 12.36, 0.36.01, “ftghikjl", None, True, False 12. What kind of program elements are the following ? ‘a’, 4.38925, "a", “main” ? 13, What will varl and var2_ store with statements : varl = 2,12162 and Var2 = 0,2,121E2 ? What are the types of values stored in var and var2 ? 2.3.4 Operators Operators are tokens that trigger some computation when applied to variables and other objects in an expression. Variables and objects to which the computation is applied, are called operands. So, an operator requires some operands to work upon. The following list gives 0 GEES brief description of the gperators are tokens that operators and their functions —wigger some computation / Joperators, in details, will be ction when applied to variables covered in next chapter - and other objects In an Data Handling. expression Unory Operators Unary operators are those operators that require one operand to operate upon. Following are some unary operators : + Unary plus ~ — Unary minus e complement not Togical negation Binary Operators Binary operators are those operators that require two operands to operate upon. Following are some binary operators : Arithmetic operators + Addition = Subtraction + Multiplication i Division % — Remainder/ Modulus ** exponent (raise to power) J] Floor division Bitwise operators & —— Bitwise AND * Bitwise exclusive OR (XOR) | Bitwise OR Shift operators << — shift left >> shift right Identity operators is is the identity same ? is not is the identity not same ? COMPUTER SCIENCE Wt ayy a : Assignment operators Relational operators : Assignment ¢ lame J= Assign quotient > Greater than te enum <= Less than or equal to oe en gaia >= Greater than or equal to Me pasion cemainder uae == Assign difference SS ‘= Assign Exponent Ji= Assign Floor division J Membership operators oe age i whether variable in i NI in sequence or Lagat notin whether variable not me Mawator in sequence 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. 2.3.5 Punctuators Punctuators are symbols that are used in programming Punetuators are symbols hat languages to organize sentence structures, and indicate the ne cst i" Programming| i neuoees © 10 thythm and emphasis of expressions, statements, and rani programming-sentence Program structure. structures, and indicate the Most common punctuators of Python programming language rhythm and emphasis af . ct ¥ expressions, statements, and are: ; propram structure "TONVQ) (108.2. "= 7 The usage of these punctuators will be discussed when the need arises along with normal topic discussions, LET US REVISE i + -A token is the smallest individual unit in @ program. & Pathan provides following tokens: keywor, deniers (names), Values (literals), Punctuators, operators and comments, & A keyword isa reserved word carrying special meaning and purpose. % Heenifers are the user-defined names for differeat parts of the Program, * In Python, on identifier may contain letters (a-2, A- digits (0-9) and a symbol underscore (J. However, on ‘all fetiersidigits in an identifier are significant. Python allows following literals : string litera, ‘eral None and literal collections), * Operotors are tokens thar rigger some computation / action when Applied to variables and other objects in 8 numeric (integer, floating-point literals, Boolean literals, special % Rancnors ore symbols uscd 10 orgonize programing. semence structures and Indicate the rhythm and emphasis of ‘expressions, statements and program-structure, 5 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. comma scence TT Anything enclosed in quote, seat integer data. Numben data. Since the data tobe! integer, real, string etc. Any or not ations reese Sata and Trucand False represent .s, a programming language ies to handleall types of data. rovers . process different types of | s string Jous data-types supported |, List 3.2. DATA TYPES Data can be of many represents string data in P with fractions represent real d dealt with are of many (ype must provide ways and faciliti Before you learn how you can lypes 8. -omplex) vai s tae ints Sfecussion of data types, you'll be ate 3 Tuple in Python thon's capabilites to handle a specific ype ef | pietionary J dota, such n e it allocates to . Z _ 4 data, such as the memory space it o hold Gertain type of data and the range of values supp’ = —— i a me - ‘, iii) List (iv) Tuy mi en ott following built-in core data types : () Numbers (i) String (i) Ls (iv) Tuple thor (v) Dictionary. 3.2.1 Numbers / / [As it is clear by the name the Number data types are used to store numeric values in Python, ‘The Numbers in Python have following core data types : (Integers © Integers (signed) © Booleans (i) Floating-Point Numbers (ii) Complex Numbers \ 3.2.1A Integers Integers are whole numbers such as 5, 39, 1917, 0 ete. (Types [ofintegersin Python 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 (missing + or- symbol means it is positive number), There are feo types of integers in Python : h . " ; . . Pees (sled). It is the ne integer! representation of whole numbers, Integers in ioe ore Hae any | lengt » it is only limited by the memory available, Unlike other | tes 8 . OSX provides single data type (itt) to store any integer, whether big or small. is si ion, i a j tgned representation, ie, the integers can be positive as well as negative, | (Hi) Booleans. These represent the truth values False and True ¢ Boolean type is a sul Bo hve He. The Be type i ibtype of plain integers, and Boolean va Fi True : tivel in integ a ol a values False and True behave like the values 0 and 1 Tespectively. To get the Boo! an equivalent of O or 1, you type bool(0) o1 thon wi mm we rT 1, you can t }001(0) or boo! (1), Python will return False “> Booleans 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), N= ay “ soa can retrieve the 0 components using attbute references. For a complex number =: e y ep real gives the ral part ' 3 imag gives the fiasinary part as afloat, not ass complex value. ng to rt 1 thing eres n Of yoo z= (142.56j) + (4 3.569) : | pra 5 i (3-4) Me will display rx par of compe e >>> z.real * curate = \ 3.8 = tet opty aint of : 93 2-Hag a gD ee co 7 4.0 I The range of numbers represented through Python's numeric data types is given below. ! Table 3.1 the Ronge of Python Numbers | Data type Range Tutegers | an unlimited range, subject to available (Siriual) memocy only | y Davies | tow values True (1) False 0) 7 4g DATA HANDING: : (virtual) memory on underlying machine architecture urbers [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 | imaginary part as ~ 2.5? | (2 wnat wt be the output oF following 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, Astring data lype lets you hold string data, iv., any number to a set of ‘quotation marks. aracters, of valid ol In Python 3.x, each character slored in a string? is a Unicode j | q=pe(1+2.53) | print (p) character. Or in other words, all strings in Python 3.x are f print (4) sequences of pure Unicode characters. Unicode is a system {4 wiat wil be the output of following designed to represent every character from every language. ode? A string can hold any type | | r=2.543.95 of known characters iv. ay i print (r.real) letters, unmbers, and special 7s [ST138G | i ; mown —All-Python (33). | print (r.imag) characters, of any known {hE Pron (3) | Wty des Python uses symbot f to Scripted language. San ae | ‘eresent imaginary part of a complex Following are all_ legal tuber instead of the conventional? — gtrinas in Python ¢ hoi Ein, strings in Python : | is Retr note above. : ~ “abed” , "1234", ' a NN TR “thon has no se inisie alt te mut aeaerty taal faa rea ~Liduacter in sparate character datatype, which miost other programming languages have — that’éan hold a single “dn Python, a characteris a string type only, with single charactersir stl: 1 aa/otvuils Seal Ge COMPUTER SCIENGE WITH PYTHON = can be individually accessed Sting ence of Characters 7 fae is a sequence of characters and each se ition of Python strings as it wil form the basis pis. Strings in Python are stored ag yy index for each location. ined in it (stored in contiguous n two-way index for using its index. Let us tetas int study the intemal structures compe TT of all the leaming of various string manipuse i Tt individual characters in contiguous tection woay individual elements of a string are the charas it Tre indo) and ag mentioned the characters of string aF® Bi ch location. ; - . iat us understand this with the help of an illustration as given in Fig, 3.1 Figure 3.1. Structure of a Python String. 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, Thus, you can access any character as t>> print (a) [1 2,34 5] st value in a list name’ wn above), you may write ty a (give en - consider statenent 1 ato, fe To change fi 59a [0] 10 change ist it >a [20, 2, 3,4 5] To change 3rd item, you may write >>> a(2] = 30 at change 3rd item pa [20, 2, 30, 4, 5) ight ; the values internally ly numbered as 0, second item of the Lists shall be discussed in detalsina ter uy, You guessed it ri are numbered from 0 (zero) onwards ic, fg, the list és interna list as 1, 3rd item a5 2 and so oq * Weare not going further in list discussion here. are not modifiable. : =a , Values of of any es Of type ist are my Jey changeable ~ one ea 3.2.38 Tuples You can think of Tuples (pronounace! as those lists which cannot be changed it. Tuples are represented as lst of comma-separated values as tiepple shyming with couple) dale type within parentheses, ¢, following are some tuples = “pe (ty 2,304, 5) change /add/delete 2 ty, i 9 2,3, 4s elements. But the valussel ge tuple are immutoble ie, 2, 4, 6, 8) i, 'e,'i,'0,'U) -non-changable;one cng, no8 8,8, 8,0) make changes toa tuple. Tuples shall be discussed in details in a later chapter. . 2.4 Dictionary Dictionary data type is another feature in Python’s hat. The dictionary is an unordered set mma-separated key : value pairs, within {, with the requirement that within a dictionary, ., there are unique keys within a dictionary). For instane- two keys can be the same following are some dictionaries = ‘ea s3, e203, >> vowels['2"] 1 ig key inside | | after dictionary name gives she corms 5 a pon from nt viding val ha ig value from the Key : walue pair inside dictionary: Dictionaries shall be covered in det: ails in a later chapter. [DATA HANDUNG cooper 9 rollowing figure summarizes the core data types of Ty(Nor. Core Date Types or or umbers None Sequences ust inieger Fteg —Complox sung Towle 1 ocean 33 UTABLE AND IMMUTABLE TYPES = mutable and immutable types, in ategorized into wv and non-modifiable types- ~The Python data objects can be broadly simple words changeable or modi 1, Immutoble types ‘The immutable types are those that can in place. In Python, the following, integers, outing pint nt sr change their value i 1s, Booleans, strings, tuples. types are immutabl concept of immutable types. In [mimutable: + intege' Let us understand the order to understand this, consider the code below = Sample code 3.1 Pes + tuples awill give 5, 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. Let's see how You already know that in Python, variable-names are just the references to value-objects i.e. data values, The variable-names do not store values themselves ic, they are not storage containers. Recall section 2.5.1 where But hold : It is not the case. 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 read 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, “ ted: three statements are execu! © Initially these pss lt vuriabes hai ' a-P res ing same vatue reference the same value ital reference same integer object. dijon Le rg FH a ree ran Each intoger valug isan Immutable object 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 3 Please noe that both 22> are valid prompts of different Python shel. Wher pe tsa 2 =: ‘Notice tho fa[) Is returning ‘samo memory addiess for un [43]: i6(5) luo 5 : po value 5, p,q. = which tn (15 is 2 prompt of de lout(a3): 1457662208 ‘means al theso are ‘hell used with Spyder 12>, referencing the samo object. is a prompt of Python ed by IDLE IDE, PyCchannDe ad others. You wil fndin{} #8 ‘our captured screenshots bit Please note, sessions, NOY Addresses depend on your operating system and will varyin die! ° When the next set of statements execute, ie P=20 oo rey aaer then these var riable nam eh | wa poets that they ree © POU o different integer objects. That °F 4 Telerence jt aa 5 will be ce will change, The original memory address cer it Same f it 0 Sameis for other variate’ te same value iv, 5 but P Wil 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 resnniie hanged Je types values can be d 9, Mutable types ; r mein python. These are + ts The mul os are mutable Them only meee YPC Dictionaries lace. . sion atteS a member 0 nd sels. falist, you ma Sets lists, ditt yy write + 6). [twill make the list namely Chk as [2 40, 6). ‘Spe, even after changing a value if In (62, id(Chk) the list Chk. is reference memory out [61}; 150295536 Cy, agaiass has romaned sama, Thal enin place ‘means the chango has tak =the lists aro mutable In [62]: Chk[1] = 49 saqche) Ae" + 150195536 Lists and Dictionaries shall be covered later in this book. 3.3.1 Variable Internals Python is an object oriented language. Python calls every entity that stores any values or} type of data as an object. An object is an entity that has cerlain properties and that exhibit a certain type of behavior, ¢y., integer values are objects - they hold whole numbers only they have infinite precision (properties); they support all arithmetic operations (behavior). So all data or values are referred to as object in Python. Similarly, we can say that a variable is also an object that tefers to a value, Every Python object has three key attributes associated to it : {i The type of an object. The type of an object determi: famed Oban object determines the operations that can be performed on 'ype() returns the type of an object, Consider this : . the object Built raed >>> type (4) Celass‘int’s ———___~ of faepersutue 4 is ernest int >>> type (a) a «Class 'int’y << ow of S‘ine’s Cam ofits la int te ine vie a Iefring toa integer il 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 7 3.4 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 feprosented by Operators and the objects of the operation(s) are referred to as Operands, er rich set of operators comprises of these types of ators : (i) Arithmetic operators (ii) Relational operators alone = ( ts ‘The symbols that tiger the Identity operators (i) Logical operators (0) Bitwise section ee (ob Shebership operators Sao, ot a Out of these, we shall talk about membership operators later as tn sie when we talk about strings, lists, tuples and dictionaries. ried oul Le, the objects of when al ata ore are referred to| 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 % rer nder : multiplication ” exponentiation t division operator ic, it requires two values (operands) to calculate binary operators, Python provides two unary arithmetic ch are unary +, and unary ~. Each of these operators is a bina! final answer. Apart from the operators (that require one operand) 3.4.1A Unary Operators Unary + The operators unary ‘4’ precedes an operand, The operand (the value on which the operator operates) of the unary + operator must have arithmetic type and the result is the value of the argument. For example, ifa=5 then +a means 5. ifa=0 then +a means 0. 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. ‘ Semetines these canbe words too, 9. in Python i and isnot are also operators. Operators en cr that act upon (Wo operands are nelees to as DMO Operator erators. The operands of a binary operator are Operators that act Binary Op rand. Together, Ue operands ate etna p e e left or right opel distinguished as the iM oan pression. op vratar and its operands constitute an expression. Binory Operators 1, Addition operator + The arithmetic binary operator + yalues of its two ‘operands. For exaniple, 4+20 results in 24 +5 (where a= 2) resultsin 7 a+b(uherea=4,b=6) resultsin 16 ands may be of number types’. enation operator when used with strings, lists and tuples, Ti fanipulation ; for lists, it will tay tgif axlds values ofits operands and the result isthe sum of, For Addition operator + oper Python also offers + as a concat functionality for strings will be covered in Chapter 5 ~ String covered in Chapter 7 — List Manipulation 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 ae in Chapter 5 ~ String Manipulation. ln uscd with strings, This fnectionatity will be oer! 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.x), the / operator worked diffi worked differently. 5, ForBootean values Je and False, recall that Python inte - eau? oh nally takes values 1 and 0 (rero) respectively so True +1 wil 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 _ Table 3.2. Binary Arithmetic Operators 1 Symbol Name Example | Result Comment + | addition 6+5 | 11 | adds values of its two operands, 5+6 UW { ~ | subtraction 6-5 1 | subtracts the value of right operand from | 5-6 | -1 _| left operand. oe * | multiplication 5*6 | 30. | multiplies the values of its two operands. | 675 | 30 _ 4] division 60/5 | 12 | divides the value of left operand with the value of right operand and returns the result asa float value {| % | Modulus (pronounced | mo-tulo) of Remainder divides the tivo operands and gives the remainder resulting i Mt | Floor division divides and truncates the fractional part from the result, exponent. (2.57 here) Exponentiation (Power) retums base raised to pow Negative Number Arithmetic in Python | Arithmetic operations are straightforward even with negative numbers, especially with non-division operators ic, “543 will give you 2 -S-3 willgiveyou 8 “S*3 will give you -15 5883 willgiveyou 325 But when it comes to division and related operators {f/,%), mostly People get confused, Let us sev how Python evaluates these, Te Prtcreoeie understand this, we recommend thal you look at the operation G&_ Geese WEY] shown in the adjacent screenshot and then look for its 6 working In [67]: 5// -3 explained below, where the result is shown shaded Out [67]: =2 = “i ) = - In [68]: -5 1/3 OMe Oo ras Bias +2 -3 In (69): «77 4 5 Out[ea}: +1.75 e In (70): -7 // 4 @ 42 © 457-2 ® -4J72 usta -2 oat =8 In (741: -7.% 4 T rs out(72]: 1 In [22]: 7% -4 72 SBR -1 In (73): 7 sf = 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. \ i sin A very common mistake is to use the assignmett oe a place of the relational operator == - Do not confuse WstOg tt operator == with the assignment operator (@). For instance, 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 valuel = 3 assigns 3 to value] ; no comparison takes place. 3.4.3 Identity Operators Operator | Usage Description There are two identity operators in Python is and is not. The identity operators are used to check if both the operands reference the same object memory ie, the identity operators compare the memory locations of two objects and return True or False accordingly. is is not aisnoth | retums True if both its operands are pointing to different objects (ie,, both aisb returns True if both its operands are pointing to same object (ie., both referring to same memory location), returns False otherwise. 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 a ls b retumns False because a and b are relerting to different objects (235 and 240) is creturss True because both a and c are referring to same object (235) tn [36]: ¢ = 235 aisb False ise : True The lds (1() )ofa, band c tel that a and © ‘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 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 ee prin NOUNS 1 ge? , ees OR (*) Operation cia of op? Result 13412 0008 1201 F 0 0 0000 1100 h 0° 1 1 - : 0 1 0008 Ge01 1 1 Q Say 1 XOR 0 produces 1, as does 0 XOR 1. (All these tions, 2 bing a pee Toputaive,) Any other combination produces 0, vege 32) *obi* | The Complement Operator ~ 3 ‘hecomplement operator inverts the value of cach bit of the operand: if the operand bits 1 the aitisO and if the operand bit is 0 the result is 1, - i This is binary coe of 15 in | 17 (92 | | | Tineaa_ The Complement (~) Operotion 2's complement j out (92. i | opt Result ~12 0090 11¢0 / ' uel | 0 » | 5 | 7 4211 0811 1 ales a { out (93): | =-(eo0@1102) | ' | _- i 46 Operator Precedence ue ent involves multiple operators, Python resolves the order of When an expression or state tor precedence from highest to execution through Operator Precedence. The chart of operal lowest for the operators covered in this chapter is given below. Description _ on 0 Parentheses (grouping) Highest 37 ad Exponentiation | * | Bitwise nor 7 || Leal Positive, negative (unary ++ —) | “hI ‘Multiplication, ion, floor division, remainder | te Addition, subtraction \ & Bitwise and ivise XOR Bitwise OR a parisons (Relational operators) identity o Com perators Boolean NOT Boolean AND Boolean OR, ae can calculate [ts 2's complement again by fellowing this ule er Whose 2's complement is giveM YON ea sicst 4, then invert all other bits. As per this to left , all Phe bits as it is UNTIL calculate 2's Pe et rif 1120012 as 00001201, which is 13. ‘COMPUTER SCIENCE WITH Prt, a Operator Associativity 4 Python allows multiple operators acb+2rete Ifthe there is not any problem as Python w what if the expression contains two operators that have in a single expression as you have learnt above, e.g, operators used in an expression have different pre sill evaluate the operator with higher precedence fig ppt the same precedence? 1 the order of operations. In that case, associativity helps deter | “Associativity is the order in which an expression (having multiple operators of same precedn, is evaluated. Almost all the operators have left-to-right associativity except exponents, (7°), which has right-to left associativity, That means, in case of multiple operators with sam precedence, other than ", in same expression ~ the operator on the left is evaluated first any then the operator on its right and so on. For example, multiplication operator (), division operator (/) and floor division operator yp JS have the same precedence. So, if we have an expression having these operators simultaneous, to-right order. Ki then the same-precedence-operators will be evaluated in le! For example, t Inf] :7*8/5//2 t Out [1]: 5.0 | Inf2) : (((7" 8) /5) //2) This fie expression is evaluate i lft to out(2): 5.0 ! right ener of openitors as evden from the 2+ expression’ endian teat eleurly marks This onder of easton t | ! | tol] :7* ( (8/5) /72) a | outs]: 0.0 | i t An expression having mulliple ** operators is evaluated from right to left, ic., t 263664 will be evaluated as 2** (34) and NOT AS (23) Consider following example : Mapes Sie the default onder of evatuaton (first expression) ' MATCHES with the second expressi { 1 efits 3 a c he Second expression whne y f Porensheses are ale ws per ° | i t 1 t 1 i | | wt NOP LIN wid etn ache po lefi-lo-right order, because exponentiation (**) stew Fihttoleft assay On 9 has | i } In (42): 3 2 (3 4 9 joan: 19683 > ' n 9: DATA HANDLING , cto af 2) OPERATORS IN PYTHON 2 - . WP Progress In Python 3.2 T ase sain For beter undersictine oe, concepts. It involves both interactive mode and. Fe ok pn tins lone op Tee eae H 8B pom ‘ " " €— Please check the proctical component-book = Progress in Computer * {Science with Python ond fill it there in PriP 3.2 under Chapter Soller) Practically doing if on the computer. ‘ » P06 LeT Us REVISE ——— 4, What i the function of logical operators 2 Write an expression Sriteing a logical operater to test if “* Operators are the symbols (or keywords sometimes) tha represent rmatks are 55 and grade is "3 specific operations. 2 What is the order of evaluation in the ¢ Aritimetie eperators carry ynetic for Python. These ore | following expressions unary + unary =, + 54,212, 9% ond +. (Darb or bed? fe Unary + gives the value of ls operand, unary ~ changes the sign of (i)x—y and ym? its operands va (ijarbecod Audition operator + gives sua of Is operands value, ~ subtracts the 3 What is the of walue of second operand from the value of first operond, gives the expression : a >= Band (ob) >a if product of is operands’ value, The operator / divides the first (jana. b-0(ipa-2,b-7? dperand by seco end returns @ float rest “performs the floor Pwiat is the tesut of is Unision, % gives the remainder after dividing first operand by cxpessans (ato) Hf Sceond und +# is the exponentiation operutor, Le. it gives base reise fo pow. ; . aoe cece, >= ral'= Le. ss thn. greater than, eval fo, iy check =", mate =" sea sult, eter thar oF ea and nt equ (i) check » meer, ate = respectively | (e) check or mate (6) mate oF EMECK ise operators are the logical operators but they work on (¢) check and not mate individual bits. (@)check and mate (¢) mate and check. yoqify operators (is, isnot) compare the memary two objects are valuate each of the above expressions referencing fe eat fe resets oe ‘Leaicol operators perfor comparisons once bast of trues of 12 order of evaluation in the ‘on expression of value. These ore ‘or, ‘and” and ‘not’. folowing expression : S65 4702-8% 324 and 5] 2=1 6 4 of not 2 == 4 and TO Ze > Ge 2 © a~155, b0:15.5 then why is $s Bis Tae white a == b is True ? ‘Boolean or relational expressions’ truth vatue depends on thelr ‘Boolean result True or False, Values’ uth volue depends on their emptiness oF nan-emptiness. Empry nuabers (such o5 0, 0.0, 0) et.) and empty sequences (such ge 2." [Je (J) nd None have truthevalue as fase and ol thers {non-empty ones) have truthovalue as tre. f t t HP 7 COMPUTER SCIENCE WITH PYTHON _ » 3.5 EXPRESSIONS thon is any valid combination of operators, ‘Anatom Is something that hay ion is composed of one oF value. Identifiers, itera i e rings, lists, tuples, and turinbtes as the a Wier, and dictionaries ete. are all atoms, An expression in Pyt literals and variables. An expre more operations, with eperators, constituents of expressions. valid combination of atoms and nplest words, an Python puts it in this way : ‘operators forms a Python expression. In s atom is something that has a value, So all of these are atoms a in Python : identifiers, Hiterals and talues-in-enclosures such as sae pe alae quotes (”), parentheses, brackets, et ples, lists, wed stehe. An’ eGpreniog dictionaries, sets vte. composed of one or more eperations The expressions in Python can be of any type : arithmetic relational expressions, logical expressions, string expres compound oxy expression: jms ete © Th © Anexpres ashe pes of operators and operands used in an expression determine the expression type, can be compound expression too if it involves multiple types of operators, Jor aebe cod is a compound expression as it involves arithmetic as well as relational as well as lgical operators. 1! Let us talk about these one by one. 1. Arithmetic Expressions Arithmetic expressions involve numbers (integers, loating-point numbers, complex numbers) and arithmetic operators. 2. Relational Expressions An expression having literals and/or variables of any alid type and relational operators isa relational expression. For example, these are valid relational expressi ions: XY, YCeR, LOX, Teg, KEIR, KeeyOR 3. Logical Expressions An expression having literals and/or logical expression, For example, these are riables of any valid type and logical operators is 3 alid logical expressions : aorb, bande, aandnotb, notcornot b 4. String expressions Python also provides two string operators + and *, when combined with string operands and integers, form string expressions. © With operator +, the concatenation operator, the operands should be of string type only: © With operator, the replication operator, the operands should be one string and onc integet- For instance, following are some legal string expressions : “and” + "then" would result into ‘andthen* - concatenation “and* *2 would result into ‘andand' - replication String manipulation is being covered in a separate chapter - chapter 5. yon HANDUNG: = | og Expressions “= 5. fotos yall be discussing 35.) BO” ion, we shall be discussing how Python eval i sec i 0 luates differ ne relational and logical expressions. String expressions, acme ot exPressions + oe we ina separate chapter ~ chapter 5, ioned earlier will be i 1a Evaluating Arithmetic Expressions 35. familiar with arithmetic expressi i a a id their baste evaluati i ‘you all are familiar ‘pressions an isi¢ evaluation rul Yo mary and middle-school yeas. Likewise, Python also has certain sof rules ieicon seu Bean expression, Le's see how Python evaluates them, pt prolvoting Arithmetic Expressions qoevoluate an arithmetic expre: jon (with operator and operands), Python follows these rules: @ Determines the order of e aluation in an expression considering the operator precedence. As per the evaluation order, for each of the sub-expression (generally in the form of cvalue> e.g. 13% 3) im Evaluate each of i operands or arguments. m Performs any implicit conversions (¢., promoting int to float or bool to int for arithmetic on mixed types). For implicit conversion rules of Python, read the text given after the rules. a Compute its result based on the operator. Replace the subexpression with the computed result and carry on the expression evaluation. @ Repeat till the final result is obtained. Inplicit type conversion (Coercion). An implicit type conversion is a conve ion performed by the compiler without programmer's intervention, ‘An implicit conversion is applied generally whenever differing data types are intermixed in an expression (mixed mode expression), so as not lo lose information. Ina mixed arithmetic expression, Python converls all operands up to the type of the largest operand (type promotion). In simplest form, an expression & Tike opl operntor op2 (e.g. xly of p**a), Here, if both arguments are standard numeric types the following coercions are applied © If either argument is a complex number, the other is converted to complex ; © Otherwise, if either argument isa floating point number, the other is converted to floating point ; © No conversion if both operands are integers: Tounderstand this, consider the following example, which will makeitcearhow Python internally toerces (ie, promotes) data types in a mixed type aritametic expression and then evaluates it. Banpie33. Consider the following code containing mixed arithmetic expression. What wll fe te final result Sinal data type 2 ches, #integer # integer flea #integer COMPUTER SCHNCE WITH Prog, floating point nunber # floating point nunber expression expression 2 db=5.0 fd=36.0 Aa (choi) /o Be fd sad * ch/2 print (A) print (8) Solution. As per operator precedence, expression 1 will be internally evaluated as : (ch + 19/40) int int Step 1 (no conversion here) step 2 (int to floating-pt conversion) Flosting pt So overall, final datatype for expression 1 will be floating-point number and the expression “will be evaluated as = ((ch +. /€b) (+150 (5+ 20/50 =(7's0 Test to flsating point conversion] =7.0159 Anu As per operator precedence, expression 2 will be internally evaluated as : B= cccearen) © eny/2) ~~ no conversion intener to floating Pt conversion ~7>> integer to floating Bt conversion ‘So, finlidbtntype for expression Hi 2 will be floating point number. on 13: DATA HANDUNG enter 3 ‘The expression, expression 2 will be evaluated as : (4 / db) ch) 72) =(((36.0/5.0)* 5L/2) [10 conversion required] = (7.245) /2) lint to floating point conversion) = ((7.2*5.0)/2) = (36.0/2) linteger to floating point conversion} 360/20 B= 180 14 The output willbe 3-4 The final datatype of expression 1 will be floating point number and of expression 2, it will be floating-point number. IMPORTANT In Python, if the operator is the division operator (/), the result will always bea lating point number, even if both the operands are of inleger types (an exception to the rule). Consider following example that illustrates it Euample 34 Consider below gic given expressions what, Will be the final result and final data type? (0) a, b=3,6 W ab-3,6 ( a,b=3,6 cebla c=b/fa c=bza Ans, (a) In expression 3 bya 0 | | ant___int Here, the operate i which abs i cy pat Floating pt (®) In expression (O Inexpression cr6//3 b Mf a foroherchien | ««CTSTS OK Ok I | related operations, €=@ | | You, yourself, can run these expressions in Python shell and then check the type of Cusing type function. a SB Eveluating Relational Expressions (Comporisons) All compari i Ihave the same priority, which és lower than that of any parison operations in Python nity, whi x Srtkmetic operations, All relational expressions (comparisons) yield Boolean values only ic, MMe OF False, Farther, chai ‘i have the interpretation that is conventional in re like ce is ix Mathematics fet cooper in Python are chained arbitrarily, 6, aq) and(q i Ot ote a §s 2. since first argument (3 <5) is True, it will now evaluate a s (second argument's) result is returned as overall In ex} i i © In expression (5 < 3) and (5 <2), since first argument (5<3) is False, sitmply its (first argument's) result is returned as overall res erguments) res a overall result ; the second argument (5 <2) will not be pxample 37 What will be the output of following expression 2 (5 < 18) and (18 <5) or (3< 18) and not B< 18 Solution. False Example 38 ‘Divide by zero’ is an undefined term, Dividing by zero causes an error in any programming, Haguage, bul when following expression is coatuated in \ Pyllvont, Python reported no error and returned the restilt as i 8 Trae, Could you tell, why ? | Ave the following expressions equal ? (5 ¢ 10) or (50 ¢300/0) | Why/why not ? Solution. In or evaluation, firstly Python tests the first | xory and not z argument, i, 5<10 here, which is True. In or evalua | Gor yp and (not 2) ) tion, Python does not evaluate the second argument if | i (xor (y and (not 2) )) the first argument is Tre and returns the result of first 2. State when would only fist argument argument as the result of overall expression. first and | be evaluated and when bo! | wvond arguments ate evaluated in | So, for the given expression, the second argument expression (30 < 100/0} is NOT EVALUATED AT ALL. e-5.d=0 ‘That is why, Python reported no error, and simply the result of first argument following expressions if a =5, B= 10 (b>candcod returned Tri 3.5.2 Type Costing You have learnt in earlier section that in expression ath mixed lypes, Python internally changes the data type of some operands so that all operands have same data type. This type of conversion is automatic, j implicit and hence known as implicit type conversion. Python, however, also supports explicit type conversion. (i) oceborc<=d (iil) (b+ ¢) <= and not (<0) | | (i dedandd (expression) where is the data type to which you want t For example, if we have (a =3 and b =5.0), then int(b) Will cast the data-type of the expression as int. Similarly, d= float(a) COMPUTER SCIENCE WITH PYTHoy, : ion of appropriate data type, in the lo type-cast your expression. The explicit conversion of aq operand to 2 specific type i called type casting. will assign value 3.0 to d because float(a) cast the expression’s value (0 float type and then ned it to d, Python offers some conversion functions that you can use to type cast a value in Python, These are being listed in following Table 3.10. Table 3.10 Python Dota Conversion Functions g To 1. | any number-conver- | integer | int() int(7.8) will give 7 tible ty; float, a (Hoating point number to integer conversion) string having digits int’347)'" will give 34 (string to integer conversion) 5 6 teg 2 | any number-conver- | floating | float( ) float(7) will give 7.0 tible type ¢.g., a float, a | poi {integer to floating, point number conversion) string having digits | number Moat('34') will pive 34.0 (string to floating point number conversion) 3. | numbers complex. | complex) | comptex(7) will give 7+0j number (ONE ARGUMENT: integer to complex number conversion) complex(3, 2) will give 34.27 (TWO ARGUMENTS - integer to complex number conversion) | 10. If a number (in string form) is given in any other base + octal or hexadecimal or binary, it can also be converted 10 integers using Int( ) asint (, base), For example, to convert a string D041" (octal bases equivalent cof) into integer, you can write int("o10’, 8) and it will give 8, Af you want to convert an integer to octal or hexadecimal ot binary form then oct( ), hex( ) or bin( ) functions respectively are there but they produce the equivalent number in string they produce the equivalent nuraber in string form ie., hex(10) will give you ‘ox A’. This value can be displayed or printed but cannot be used in calculations asit is not number. Howevet combining hex( ), oct( ), bin( ) with int ( ( ) €,, 0 convert to float, one may write \} | float () Solved Problems me What are data types ? What are Python's buil Solution. The real life data is of many Programming languages provide ways a in core data types ? 'y types. So to represent various types of real-life data ind facilities to handle these, which are known as data types Fython’s builtin core data types belong to : ‘© Numbers (integer, © String © Tuple Moating. point, complex numbers, Booleans) * © List . © Dictionary Which data Aypes of Python handle Numbers ? Solution. Python provides follow (@ Integers (til) Floating-point numbers ing data types to handle numbers (i) Boolean (iv) Complex numbers les, es, Sit oor 3: DATA HANDING ; 1 Why is Bavdean consilered a subtype of integers 2 solution. Boolean values True and False inte considered! equal to Tand False equal to 0 pool()) function, they ret entify the data typ ‘nally map to integers 1 and 0. That is, internally True is ee (ero). When 1 ond 0 are converted to Boolean through 1m Truc and False. That is why Booleans are treated as a subtype of integers. of the valies given below : 3H, 13.0, 13, "13", 240), 13, 13,1321 13.2) Solution. 3 integer 3] complex number 130 Floating-point number ny string “3° String 240) complex number 1B integer 113,2) List 13,2) Tuple what do you understand by teem ‘inunutable! ? Solution. Immutable means unchangeable. In Python, immutable types are those whose values cannot be changed in place. Whenever one assigns a new value 10 a variable referring, to immutable type, variable’s reference is changed and the previous value is left unchanged. ¢8., xo3 x25 + >} value 9 fs untouched and x Is made —.5 fF toretor to new valuc. hat wit! be the output of the following ? print (Len(str(17//4)) ) print (Jen(ste(17/4)) ) ; because and Jen(str(17/4)) sense) eee a lenc) = len('4.0) Vial wilt be the output produced by these ? . (0) 124 (yA (HA (LOM (OV TOI (4.0% Solution. (230 (1 (2 (35 30 (20 8 Given thai variable CK is bound to string *Ramau” (2c, CK ~ "Raman"? What willbe Me output produced by following two statements ifthe input given in “Ramat 2 Why ? DK = input("Enter names") Enter nane = Ranan @DK-=ck —() DK isCK COMPUTER SCIENCE WITH PINON ceul will be as Solution, The ewtpat peo (True () False sro re ena bth DS CK strings ane always bound to fesh memory € string in memory Thuis DK == CK produces True as strings af Dut DK is CK produces False as they are bound to diffe 2 Explain reason boul vntpat of every Hine Identical strings "Raman’. Dut inpyy jable are bound to ‘ alu Identical to some o'er enisting ven if they have ¥% ide sent memory addresses, 9, Wheat wil be te eutput of fottowing conte 5 <5 or 10 54 100rS 5 < (100 5) 5 «(Sor 10) Solution, 10 true P True i False Explanation Line 5<¢5 or 10 precedence of < i higher than or alse or 10 +10 because or would evaluate the second argument if fist cent is False oF False Line? $30 or 5 precestence of « is higher than o¢ True or 5 ( = True oor would return first argument if it is T Line3 $< (10 or 5) =5c10 10 or & retums 10 since 10 is true; = True | Line# $ © (5 or 10) =565 5 or 10 returns 5 since 5 is trey, = False 10, What will be owtpu | wi ke Out produced by the three expressions ofthe following cote ? bes | c=2 d=-10 a+bscratc-beg Strasb+erasc- bed) « len(str(a+bsc>as “true? © = B* Ad) = ren(ste(bo01(1))) ee @ =n ION ~ Ut inpue « existing if first |p: DATA HANDUNG True False True solution. ewild Python produce if for the fo 1. What would Python p Fr te flowing ete the ipa given i Hello Gi) just return Key (i 0 (0) 5-5 cole bool (Anput("Enput")) ond 20623 = Solution, () Input : 11 would yield 'Y Pressed, no input given bool (11') and 10 ¢ 3 True and 1011 = True (i) True [For the same re: aon as in ()] (Gi False because when just retum key is pressed, input ise, emply sting, hence expression becomes, bool(**) and 30< 11 False and True = False (is) bool ("0") and 10.11 (Please note ‘0? isa non-empty string, True and True and hence has truth value as true pat) = True bool ('5-$') and 10 ¢ 12 = True and 10 < 31 = True sg coude ? Explain reasons) 12 What wld be te output of as345/8 b= int(3 + 5/8) c= 34 float(5/8) d= 34 Float(5)/8 e234 5.0/8 f = int(3 + 5/8.0) print (a, by ¢, 4) es #) Solution. The output would be 3.625 3 3.625 3-625 3.625 3 Explanation Linel a 2345/8 = 3+ 0.625 a= 365 COMPUTER SCIENCE Wi py "| fal s ¢ +5/8) ill drop the fractional part) 6 Uy ae ofan tint() will drop the frat i o sin Bt wtye se ee = int 8.625) ° ae bes atee 1 as Line ¢= 34 float(5/8) aes c=3 + float(0625) ee =3+ 04625 re : “i o0 = 3.025 ‘ oe ‘ ie: at (5)/8 u Se = 0625 bee operand is floating port ig al #34065 « We 23.625 ai Bs LUneS = 34 5.0/8 « 25 same reason as above) tt #340605 Game re a = 3.025 pte thee i (same reason as above) ysl the Line 6 = int(3 + 5/8.0) 1 = mt @ + 0.625) fr3 it , 5. What wit te te output produced by following code statements ? 4 mle ¥ () 87/5 (t) 8715.0 Sion () (© (6750) = (87 5) (9 (87 5.0) = int (87 150) istheo £2 (Moe 6.0) = (871150) : ane, Solution. (2) 17 (0) 17.0 (¢) True (d) Truc (e) True 4. What wil Ne the output produced by following evde statement ? State reasons(s) @ () 17%5 () 17% 50 (4) 07 % 5) is (17 (17 % 5.0) is (17 i) True (¢) True (j) False (9 (17% 5) == (17 % 5) (0) (17 % 5.0) == (17 % 50) Solution. (a) 2 (6) 2.0 (¢) True ¢ Both (c) and (e) evaluate to % 5.0) - 9 ey True because bath the operands of == operator are same values (2#=2in (©) and 2.0 == 2.0 in (¢), \ (@) evaluates to True as both the operands of is operator are same integer objects (2), \ oP Since both operand expressions evaluate to same integer value 2 and 2isa small integer value, both a are bound to same memory address, hence ie operator returns True, Inf, even though both ope ands evaluate lo same floating point vak False because Python assigns diffe 2.0, the is operator retums “ent memory address to floating point values even if thelr exits a same value in the memory. 1 t rin oth rns 3 Vi, What wit! be the oulpet of following code ? Why ? 4g: DATA HANDUNG wnat will be the output produced by the fetows ing code st (a) bool(0) (b) bool % (©) bool) Glen State reasons, (bool) (8) bol0.0')—() boot) MI) e) bool(* ) solution. (book 9j) {@) False, Integer value 0 has false truth value hence by (0) True. Integer value 1 has true truth value hence ean ) converts it to False. (9. True. ‘0’ is string value, which js IC ) converts it to True. converts it to True, an ‘ “on-emply string and has a true truth value, hence bool{ ) ( True. Same reason as above, (9 False. *is an empty string, thus has fals. 1s false truth value, hence bool i » hen I() converts it to False, (p False, 0.0 is zero floating point number ai Fal mber and has false truth value, hence bool( ) convertsiit to (g) True. Troe. Y isa non-empty stri vi ™mply string hence it has true truth value and thus bool( ) converted it to (h) False. 0j is zero complex numbe: Le P nber and has false truth value and thus bool ) converted it to {) True. ‘Oj’ is non-empty stri = The. J pty string, hence it has true truth value and thus boo( ) converted it to 1 Wat willbe the output produced by these code statement ? (a) bool(int(‘0")) (@) bool{str(0)) (6 bool{float(‘0.0')) (@) bool(str(0.0)) Solution, (a) False (b) True (c) False (d) True () 13 or Jen(13) (i) Jen(13) or 13 Solution. O B because or evaluates fist argument 13's truth value, which is tre, and hence returns the result a8 13 without evaluating second argument, (i) error pecauise when or evaluates fist argument fen(13), Python gives error as Ien() works on strings only. zo) and height(l) of 4 p Program to read basellengi (D, width parallelogram and calculate its area and height (n> ‘width (¥) base (I) COMPUTER SCIENCE WMH Prag, Solution gecinpurtenter base/length of the paralelogrom : ")) hs Fieve anput( "Enter width of the parallelogram : *)) i we row anpue( “Enter height of the parallelogram ¢ “)) areas 1*h perineter = 2*1 + print(*The area 0 print(*The perineter of 8 aw given parallelogram is :", area) iven parallelogram 4s :", perimeter) : “The sample run of above program is as shown below : enter base/length of the parallelogram : 13.5 enter width of the parallelogram : 7 Enter height of the parallelogram = 5 the area of given parallelogram is : 67-5 The perimeter of given parallelogram is : 41.0 * GLOSSARY ee B Atom Something that has a volue. coercion Imalict Type Conversion Expression Valid combination of operators ond atoms. Explicit Type Conversion Forced data type conversion by the user. Immutoble Type A type whose value is not changeable in place. \ Implicit Type Conversion Automatic Inteinal Conversion ol data type lower 10 hi ‘Mutoble Type A type whose volve is changeable in place. Operator Symbol/word thot triggers an action or operation Type Casting Explicit Type Conversion Assignments a nena Type A : Short Answer Questions/Conceptuol Que: 1, What are data ty 2. How y integer low many integer types are supported by Python ? Name them, 3. How are these ii en another? 33, 33.0, 33), 334 ow are these numbers different from one anather 33}, 33. + 33.0, 33), 33+) 4. The complex numbers han ers ave two paris : i | pats represent Vo parts : real and imaginary. In which data type are real and imaginaty 5. How many sin 8 tyPes does Python § What will ollowing code print? ? How are they different from one another 2 str = "Hell ot str2=""'He1y en Print(len(stri) > len(stra)) ns es ? How are they important ? a x 3: DATA HANOLNG a | What ore fmmutable an mute types ? Ls a , immutable S what are three internal key-attributes of Mutable and mutable types of Python. a value-variablej fable in Python 2 E for is operator, they a2 Explsin with example g, Bp it trae that if two objects return True he . u wil these values equal ? Why/why not ? *Y will also return True for =» operator? yo Are (9 2 and 20.0 Gi) 20 and int20) str(20) and ste(20.0) (fv) ‘a* and “a” sy, What isan atom 7 What is a expression 2 is the difference between implicit ty 7 who plicit type conversa ; Tro objects (ay a and 8) when compared wing nea OPE conversion? Compared using is operator. Why Be 'B ==. return True, But Python gives False when fin, a= bis Tre but why is a 14 Given ste] = "Hello", what will be the st OL @) sted 1] ste [5] ste} (str) 15. Ifyou give the following for strl = "Hello", why does Python error? stri[2] = "p" Taian ponte 16 What will the resull given by the following 2 (iype (63) (type — 3) type G6" 3) type (13) (type (HS) type (6 % 3) 12, What are augmented assignment operators ? How are they useful 7 38. Differentiate betwee opa3ye, 49, Given three Boolean variables a,b, cas : a= False, f= True, c= False. Evaluate the following Boolean expressions : (a) band ¢ (bore (@)motaandh — (@) (@and b) or note (@ not band not (a or 0 () not (not bor not a) and gor a 20, What would following code fragments result in 7 Given x=3, | @isx @xe4 (x= Wd) x—=3.0 — (¢) “Hello” = “Hello” | ()"Hellot > “hello” A= (WAB—=P_— xT and A>. 21. Write following expressions in Python as le Gath © fare (yd QG2=AF R= Uti. for sq) se math.sgeO] 3 (O(x-hy + (y- Wary aa™ wy Rin 7 int(#) produces error. Why ? does not return error. Why ? int) produces error but following expression having int) in ne mrt? oF ine” hte expression to convert the values 17, lenCab) to ® integer (if) str (iii) Boolean values ' Erauate and Justify : (() 22/17 #37/47 488/83 | Bante: @y2207.0—2007 (i) 220770 ~it@2.0770) - Baluate and 7 j) 0 and None (fi) True am +4) false and None (i i) ten ('375')""2- ; (iy 2277 ~int 22.097 ane justify .d None (jv) None and None. COMPUTER SCIENCE WI Pity, gor’ rand @ a sor 3-4) “poet and not (2 ** re ror not ‘True or 1 == Land False or O == 0 for each expression that is sucessfully evaluated, determine its value andj valuate 5 = fe weucesstl expression, state the reason (a) len(rhello") +7 25/5 0° 20/10 (hy 3.507 5O/(S (+2) 35 (e) 50/5 = (34 29) OF (2° (24 Clen("01"))) 30, Waite an expression that uses exactly arithmetic operators with integer literals and produces result as99, Bh Add parentheses to the following expression to make the order of evaluation more clear, yx4er@ and yX100!=0 or y%400 == 0 Type B : Application Besed Questions 1. What is the result produced by (i) bool (0) (#) boo! (str(0)) ? Justify the outcome. 2. What will be the output. if input for both the statements is 5 +4/ 6 == input ("Value 1:") G == Int(input ("value 2:")) 3. Following cade has an expression with all int a,b, c#2,3,6 values. Why is the result in floating point form ? daarb*c/b print(d) 4. What will following cade print ? @)a=vae3 (b) a=3 bevas3 b«3.0 Print (a, b) print (a == b) print (a is b) 5, What will be out put produced vis Mena? by following code ? State reason for this output. wD DATA HANDLING: What will be output produce ae5-4-3 e323 print(a) print(b) 4, What would be the output produced by a,b, = O02 d-0.3 ‘ype eratbeced feasbec print(e) print(f) What will be the output of folloy 4 By following cote ? Sta, ale reason, following code 7 Why 2 p Python code 2 $99, asi2 be7.4 a-eb print(a, b) ate24c print(a) btratec print(b) 8. What will be the output of following code ? xy=4,8 | zexiyty print(z) 10 Make char pression for = of prev cannot change the operators and order of (Hint. Use a function around a subexpression) 1. Following expression does not report an error even if it has Problem : 3 or 10/0 What changes can you make ta abo 2 Whats the output produced by following code ? a, b = bool (0), bool (8-6) ©, d= str (0), str (0-9) Print (Len(a), 1en(b)) Print (Len(c), len(d)) Given a string s = "12345". Can you writ ‘String s ic, the program should be abl Mint, Uses indexes and convert to integerl Tretict the output if ¢ is given input as TE a= True beecs Print (a == b) Print (a is b) * is _ question so that the output produced is zero, You ables. a subexpression with ‘divide by zero! so that Python reports this error ? axpres i shown inside the Jan that gives sum ofall the digits: ean expresion Mul a 1 (HDI) ie to produce the result 3S c= ste (3) d= str (0) print (¢ = 4) [ print (cisé) PS input ("enter °7) print (¢ == ©) print (¢ 45 @) 45, Find the errors(s)- COMPUTER SCIENCE WITH PYtHoy (y) a= bool (2) chart” @ (ane = “HariT b= bool ° int. (name) int (a == false) pri a ss nane(2] = °F" print (b == tu int (nae) print ¢ wy pends print (type (int("123"))) print (type (int("Hello"))) print (type (str(*23.0"))) print (type (Pi) print (type ("3-24") (ype (float ("3-14"))) . ‘three point fourteen"))) o print { print (type (Float( (p print ("Hel10"/2) (@ print ("Hello” + 2) rine Cell2" / 2) } print ("Hello + "2") print ("Hello" * 2) Type C : Programming Practice/Knowledge bosed Questions 1. Write a program to obtain principal amount, rate of interest and time from user and compute simple interest. 2. Write a program to obtain temperatures of 7 days (Monday, Tuesday ... Sunday) and then disply average temperature of the week. : 3. Write a program to oblain x, y, = from user and calculate expression : 4x*+3y"+9z+6n 4. Write a program that reads a number of seconds and prints it in form : mins and seconds, ¢.g., 200 seconds are printed as 3 mins and 20 seconds [Hint use // and % to get minutes and seconds] 5. Write a program that reads from user ~ (i) an hour between 1 to 12 and (ii) number of hours ahead. The Program should then print the time after those many hours, Enter hour between 1-12 ; 9 How many hours ahead : 4 Tine at that time would be : 1 ¢clock & Write a program to take year as input and check if itis a te 7. Write a program to take two numbers and print j or not. & Write a program to take a 2-digit a 2-digit number and then v 1s 25, the prograin should print 52, Patiheres 9. Try writing program (similar to previ ould pee em iar to previous one) for theee digit number ie, 10. Write a program to take two inp date is. For simplicity, take 30 d then it should print "Day ‘AP year or nol. ‘ersed number. That is, if the input give" if you input 123, the progr@™ ls for day, month ar lays for all ri then calculate which day of the year, the gv Of the year : 33%, ‘months. For example, if you give input as : Days, Monti? Pe Conditional and Iterative Statements ay Ws Cuavler 44 tmvoducvon 4.5. The Statements of Python 42. Types ef Statements in Python 1.6 Repetton of Tasks — A Necessity | 43. Statement Flow Conta! “a7. Tre Range Euncion | 4a Program Logie Develop ent Tools 4.8 eration ! Looping Statements le 41 INTRODUCTION from beginning, to end. But not many Programs seein in strict oreer from beginning (0 end. POR IMS depending upon Mf the available alternatives of even repeat a set of Generally a program executes its statements | execute all their state the need, can choose to execute one he statements, To perform their manipulative imigacles, programs necd tools for performing | repetitive actions and for making decisions Python, of course, provide such tools by providing, | statements to attain so. Such statements are called progran control statements. ‘This chapter dlscueees such statements in details, Firstly, selection statement if and later iteration 1 statements for and t vr ” vhi ¢ hired in . This chapter also discusses some jumP statements of Python ssc are biaak and ont en 1 en ho cOMPUTER SCIENCE WITH PYTHOW _ 5, "122 4.2. TYPES OF STATEM! i ions gi ements are the instructions BV Statements ae te ing ec within a Python prope ind of action, be itd n any kind o| dat perform’ Mtements form the smalig, belong to one of the follescing ing actions. Se be it repeating acter an : fx. Pytlton statements © movements, 2 executable unit three types : site © Emply Statement © Compound Statement giatement (Single statement) ich does nothing. In Python, 1. Emply Stalement hich does nothing an tis the ‘The simplest statement empty statement is pass statement. n Python does or winters a pass statement, Wherever Python encounters a pass statements PSN SD cxnenan stern | nothing and moves to next statement in ol Thegaesinemen Prien i A pass statement is useful in those instances where 1 © gue eee et | syntax of the language requires the presence of a statement SPN NTN bul where the logic of the program does not. We will see i loops and their bodies. atement W! enply staterment ita siavemer” It takes the following 2. Simple Stotement . te; follows Any single executable statement is a simple statement in Python. For example, following is a : simple statement in Python fname = input ( "Your name" ) Another example of simple statement is print (name) # print function called As you can make out that simple statements are single line statements. \ 3. Compound Stotement A compound statement represents a proup of statements executed as a unit. The compound | statements of Python are written in a specific pattern a shown below : : That is, a compound statement has : j 9 a header line which begins with a keyword and ends a os i } with a colon. ® a body consist ° A compound statement in Ih indented? cide rhe eee Python statements, each Phan tor aheasereren wih | body are at thesprs reader line. All statements in the 4 lon (:} and a body com You'll ata tel of indentation, taining a sequence of state: fou'll learn about some ments at th level of other com, ; he same level white) in this chapter, Pound statements (if for, indentation, | :CONDITIONAL AND ITERATIVE STATEMENTS ; jp. STATEMENT FLOW CONTROL mm, statements may be exec a program, sl nay be executed sequentially, i M2 Sonny agus Proves conse a vent selectively or iteratively. Every ogrammi iguage provides construct }port sequence, selection or iteration, atus discuss what is meant by sequence, selection of iteration constructs sequlee ‘The sequence construct means the statements are bei { eet cequentially, This represents the defvuy mes | executed seq! y. This represents the default flow of ftatement (see Fig. 4.1). , stone? | Every Python program begins with the first statement of Wests gram, Each statement in tum is executed (sequence s construct). When the final statement of program is executed, = the program is done. Sequence refers to the normal flow of vo} control in a program and is the simplest one, Figute 4.1 The sequence construct. Selection The selection construct means the execution of statement(s) depending upon a condition-test. If a condition evaluates to True, a course-of-action (a set ‘of statements) is followed other another course-of-action (a different set of statements) if followed. This construct (sefectiow construct) is also called decision construct because it helps in making, decision about which set-of-statements is to be ex ted, | Following figure (Fig. 42) explains selection construct ' One couserot-action [Sent -—— construct. Figure 4.2. The selection real life so many’ times ei the traffic signal ection in your Te" ellow then wait ; and if the signal light is You apply decision-making oF 5 light is red, then stop; if the traffic signal light is ye Breen then go. jon/decision-making. You can think of many such real life examples of selection/decision-making, COMPUTER SCIENCE WITH Prion t tse tition of Comiion ? y P1424 eas ion (Looping) erat . " ‘The teration constructs mean AAT TT a b setof.statement depen pe a is nh p time a cor cnition-test. THN the u oon crnse depending upon the loop) + =inn Tove (or ements are repented agai 2 sees saat a te conn BECOMES — 2 ey te repli stops: THE aT iteration construct is also called looping iteration construct 7 4.3) illustrates an Figuie 4.3 The iteration construct. The adjacent figure (Fig. iteration construct. iy orn in i the body of the loop. The epeated again and again is called y e set-of-statements that are repeated again afte top| aan on which the execution or exit of the loop depends is called the exit condition or test-condition. : You can find many examples of iteration or looping your mother cook chapatis or dasas or appanis for you. around you. For instance, you often see y Let's see, what she does for it: () put rolled chapati or dosa batter on flat pan or tawa (i) tum it 2-3 times (ii) once done take it off. Repeat the above process (steps (9, (i), (i) for next chapati/dosa/appam. This is looping or yo iteration. You can find numerous other examples of repetitive work in your real life ¢¢., washing clothes; colouring in colouring book ete. ctc. Every programming language must support these three {ypes of constructs as the sequential program execution (the = default mode) is inadequate to the problems we must solve. yo Python also provides statements vo, Python also provides statements that support. these constructs. Coming sections discuss these Python if that supports selection and for and while that support iteration, Using these statements you ean creale programs as per your need, statements — 1. What ia statement ? How many types | Of statements are therein Python ? i 2 What is the significance of a rican ss ‘ met sg r Bat before we talk about these statements, you should 3 Mots 2 omen scenen 2 gpe_ MOWERS tools that wil help you decide about the ogi! eo emgmint nett Hine ee Prtblem ie, the algorithm, For this, there are 4. What are the three con: (cols available. I i io 1% itis le. In the follow: ye are govern statement flow? “going to talk abo s = Flowchart, det § si ut three such taols — Floweharts, decisiot © wnt bee rees and pseudocode, " looping constructs ? for selection and = CONDITION jet CONDTIONAL AND TERATIE STATEMENT 125 qs PROGRAM LOGIC DEVELOPMENT TooLs afore developing the solution of a proble analyze the given problem and tecide about siesta sryer of these subtasks, In other werds, problem and represent il through vario an algorithm is a step-b i @ program, you should read and Sut basic sub-tasks newde! to solve a problem and the You figure out the algorithm for the solution of a given ious logic development tools. step procedure (well-d % y elledefined jnstructions) to solve a given problem. Tec tance, the Ss algorithm to find the remainder of giventwonumbersis: “*, ciowhm, 2 Hee bye Tape fst te perp a . Input second nanber. 2 3. Divide first umber with second number and store the remainder as thint member. 4 Display the result (the tlrint munber, An algorithm is a set of ordered and finite steps (the subtasks) to solve a given problem. Consider another example that extends the above problem ~ 1 first number is divisible by second number or not 1. Input first nun ng the same logic determine if the 2. Input second number. 3. Divide first number with second munber and store the remainder in thin! number 4. Check if the third number is 0. (a) I Yes, Display ‘the first number 1S divisidl (b) IE No, Display ‘the first munter IS NOT le by seconul 1 {As you can see that the sublasks in above algorttims ane shown in bold letters and there is a proper order of carrying, out these steps/subtasks “Algorithms are commonly weitten out with tools like pseudacade, flow charts, or tectsion trees and tables, Let us talk about these tools one by one. 1 Flowcharts sentation of an algositlim. A flowchart shows different subtasks flowchart isa graphice OP “hows commonly used flowchart symbols. With different symbols. Following figure (a) <> ome [A flowehart is 2 graphical represen- ayecess =) sent iets om: a Flowchart symbols. (VO) operation (taking input and showing outpul). 4 internal operations like initializa- Process Ls Figure 4 © Use Data symbol for Input/Output stint © Use Process symbol for any 'YP© ‘of computation a tion, calculation ete- . read) © Use Subprocess symbel t0 invoke a procedure written already COMPUTER SCIENCE WITH Pry ” thm (determine ifthe first number is divisible py 5 e above algorithm ‘The Movchart for the abo umber oF not) will be = Sr to fow ‘of contel or eideret steps remainder = (9% z iS NOT Spl te est ruber IS HOT Z_ sista by tne saan eambe ‘isploy Ye frst number's 7 aati byte se arto / With flowcharts, a programmer «can pictorially view the sublasks of an their execution. algorithm and the order 4.4.2 Pscudocede Pseudocode is an informal language thal helps programmers describe steps of a programs solution without Programming language syntax, Pscudocode is detail (algorithmic) desig Now consider { ne Pseudocede is an informal way using any of describing the steps of a a “text-based” Program's solution —witheut ‘ook A pseudocode creates an” ssing any sinet orogeny w OF a rough draft of a program that gives the idea o {ineeaze syntax or undering the alpen ant OF 8 preg Otome technology considerations. how the algorithm works and hiv the control flaws from one step to another. ! For example, consider the following pseudocode : TF student's marks is display “passed” else display "fatleay ereater than or equal tose The above pseudocode gives you an idea passed ot fated compari how a program determ ing the marks of the student es whether a student has 10 ITERATIVE STATEMENTS CONDITIONAL AN 127) oe nesamealgorithm that we talked above (detem consider or or not). The pseudocode of th te Uf the first number i soa momen ¢ of this algorithm can be “en ber is divisible by spot fart mumber 30 variable firstnun, see second ruber in varSable secondnun Minder « Firstnus modulus secondnun fgthe renainder 1s @ display ‘the First nunber IS divisible by second nunber* | as. i S modulus to get resainder display ‘the First number IS NOT divisible by second nunber* riese note there are no standard rules to write a pseudocode asi is totaly representing, an algorithm, P de as it is totally informal way of 143, Decision Trees Decsion trees are a way’ of presenting rules in a hierarchical and sequential structure, where used on the hierarc! Let us consider a familiar example. You all know how di marks, | y of rules, certain esrteomes are predicted. jons are determined based on Marks oivsion 260 First \ | 0-40 snond | s0-%0 Thind | <4 Failed | Now consider following, diay 7 Marks more than fr ecnt'0 60 y : t : s 8 Marks more IN First civision” | req t0 50 race | sen | as more han second ion | frequalte 40 ' 6 readable ? Dees it make sense ? Isn't it more COMPUTER SCIENCE VATH PTHON |, archical structure of outcomes baseg ryan's old friends may visit him, A Decision tree Certain unl words, ads posible rules base des pas 3 me Ter igi noir ypc sittin. Aan BE spelt and rstayingin the seo! ete TH Sunday Se Aryan has decided to spend his Sunday’ 38 pe an i hem for ety tour. Whey don't come, he will play FEA wil go with her age, depending upon money 1n His pocker, he fre promisesor il spl eo 299 rend, ‘an outcome If his friends visit him, he i with his roommate I his roommate 15 nay cat out ino restaurant oF from sia ght a decision tree Now this situation can also be depicted through 2 decision i] ote ‘A decsion tree is 3 toc! tg etn epreentatienrched sete Of outcmes bated on cera e ie cules. cxytou Roonmate tee Pay FIFA Honey pocket Alot No menay 200) Notmuch (e100) 200"360) Estown Ealtn Eat maga! aesiautan, hostel cata roses So the rules for spending Sunday as per this decision tree ean be written as If old friends are visiting, go for city tour Or Hold friends are not visiting and roommate is free then play FIFA, Or If old friends are not visiting and roommate is not free and has a lot of mone 500) then eat out in a restaurant Or If old friends are not visiting and roommate % 200-300) then eat in the hostel cafe Or Ifold friends are maggi noodles. Snot free and has not much money (roughly not visting and roommate isnot free and has no money (less than 100) then eat Decision trees are majorly used in le After learning about these logic dev iterative statements, 'aming algorithms of mode: M programming languages ‘elopment tools, {et us learn about Python's selection and few chars 3 we dstement 5 Fe Bey ent, iF Frag TMi n of 4 CONDITIONAL AND ITERATIVE STATEMENTS 129) js. THEIE STATEMENTS OF PYTHON if statements are the conditional st, i constructs (decision construc), #19 Python and these implement selection ‘Anifstatement tests a particular condition ;j jg followed ic, a statement oF selof. evaluates to false), the course-of- pefore we proceed, it is ard logical operators as tole inall forms of if statement, w ralue trite rat Collectively false jas collectively. ‘Action is ignored, \ditionals in this chapter. Also, please to Boolean value True as well as truth '0 Boolean value False and truth value ent, we are using trueto refer similarly, false here will refer t 45,1 The if Statement The simplest form of if statement tests a condition and if the condition evaluates to true, it carries out some instructions and docs nothing in case condition evaluates to false. ‘The if statement is a compound statement and its syntax (general form) is as shown below : if =" and ch . print ("vou entered a d8@lt-") ing i comparesits value een “The above code, after gelling ree ie ere aust will execute the statements in the if-nq)! 19 t0'9 ie, te condition evalua! : ing" digit! that is, it will print a message saying "YOu ened sg oerthecthe: two i fer another example that uses ) if value of ch falls between Now coi che nput (“Entera single character :' 1 the control wil direely reach f0 Apis condition ts fae tho a rey ec Behe Aang if teen ring eb eT serent print ("You entered a space") Af ch >="@" and ch <*' print ("You entered a digit.") a ‘The above code example reads a single character in variable ch. If the character input is a spa itflashes a message specifying it Ifthe character input isa digit, it flashes a message specifyingit ‘The following example also makes use of an if statement : ‘Az int ( input (“Enter first integer B= Ant ( input ( “enter second integer Af A> 10 and B<35: C= (A-B) * (A+B) print ("The result is", C) print ("Program over") 4. Tris statement snot part of if statement as it not indented atthe sare tevel as that of fly of if statements, The above program has an if statement with two statements in i i p in its body ; last not part of if statement. . pn salem Have a look at some more examples of conditional expressions in if statements : (@) if grade =='8 print ("You did well") # comparison with a literal © Sfarb: # comparing two variab: Print ("A has more than B has") me () : ( ifx: . # testing print (‘xhas truth value as true” ‘truth value of a variable fori if al Tora Space, ingit nentis 14: CONDITIONAL AND ITERATIVE StaTeMENTS row consider one more test condition : Af not x: not x W411 return print ("xhas truth value as false this tine) me lo nothin, it seating if the condition evaluates to false and 45.2 The if - else Statement ‘Tis form of if statement tests a condition and if the condition evaluates to tr i luates to true, giotements indented below if and in case conditi it carries out condi . indented below else. ition evaluates to fals, it carries out statements ‘The syntax (general form) of the if-else statement is as shown below if «conditional expression> : statenent [statements] The block below if gets else; << _ ons ater both fart ene executed if the condition eatensit evaluates to true and the Block below else ets [statements] executed if the condition evaluates to fal. For instance, consider the following code fragment : ifar=O: print (a, “is zero or a positive number") else: print (a, "is a negative nunber") For any value more than zero (say 7) of variable a, the above code will print a message like : 74s zero or a positive number ‘And fora value less than zero (say’-5) of variable a, the above cade will print a message ike: 5 isanegative number Unlike proviously discussed plain-if statement, which does nothing when the condition results into fase, the if-else statement performs some action in both cases whether condition is true or false. Consider one more example : Af sales >= 10000 : discount = sales * 0.10 else : discount = sales * 8.05 ates discount! as 10% of sales amoutt The above statement calcul: “ mn ‘alaulates discount as 5% o| itis 10000 or more otherwise it ¢ Sales amount, purer SCIENCE WITH PYTHON come oa ipelse constructs of Python. Following figure (Fig. 4.5) illus ifelse com ' + ~ : Fost se aN ett rise may max=y ifz>max: max =z Print (“Largest nunber is", max) The sample . Enter first number : 7.235 code ee oe Enter second number : 6.99 nase | Enter third number : 7.533 Largest number is 7.533 35 29 33 “1 CONDITIONAL AND ITERATIVE STATEMENTS 4.2 Prograrthat takes a number and checks whether the gi en number 1s odd or even. Input nu Tf nummodulus 2 45 equal toO then display num is even else display num is odd numis even mum Decson tee bess Flowchart Decision Tree Code in Python runs int ( input( “Enter an integer :* )) ‘Sample run of above program is as shown below : if num & 2 == print (num, "is EVEN nunber.") ‘ else: |) Ener an integer: 8 print (num, "is 000 number.“) \" is EVEN number. p* Program that inputs three numbers and calculates two sums es per this = Sumt as the sum of all input numbers +f one are duplicate mumbersin the input, ignores them eg., Input of numbers 2, 3, 4 will give two sums as 9 and 9 4, will give wo sumnsas 8 and 2( both3’s ignored for second sum) itive two sumsas 12 and 0 (all 4's ignored forsecond sum) ing te given problem, It elternatioe’s pseudocode is given Sum? as the sum of non-duplicate numbe Input of numbers 3, Input of numbers 4, 4,456 Here we are giving two different ways of sl and 2nd alternative’s decision tree is given : sum1=8, sum2=8 input three nunbers as nun, numZ, nun sun 1=numl + num2 + nun3 4f nun not equal to nun? or num3 und = sun2 + num $f nuna not equal to numl or num sun2 = sunz + nun 4# nun3 not equal to num or aun2 Sund =sun2 +num3 ‘Sisplay sum and sum ‘Alternative 1 suai = sun2=@ : runt = Ant(input (“enter nunber 2 +") rund « int (Input(“Enter nunber 2 =") run3 « Ant (input (“Enter number 3 : “)) sum] = nual + nun2 + nun Af num |» num? and nur |» nun3 = sun? +« nun 4 umd [= nurmd and num? f= mum3 = ssum2 + nun2 Af pun3 T= rum and rund |= nun? : sua? += nun3 print(*Nunbers are", numi, nun2, nun3) print("Sun of three given nunbers is", sun) print("Sum of non-duplicate nusbers is", sun2) Alternative 2 sul = sun2=0 fhun2 = int (input ("Enter number 2 : “)) rund = {nt (input(“Enter nusber rund = int (input(“Enter nurber Suni = num + nuz2 + nus} Af num «= nun? : Af num3 |= num = sund += nun3 else: Af num == und : sun2 += nun2 else: Af nun2=*nun3 : Sun2 + nun else : Sun? += nun] + num? +num3 Print("Nurbers are", num, num2, nun3) Print ("Sun of three given numbers 1s", sunt) Print ("Sum of non-duplicate numbers 1s", sunz) COMPUTER SCIENCE WATH PYTHON _ 5 Please note thatthe pseudoc ‘and decision trees a given Jost for understanding pur | to make you understand how easly YOU et the logy [behind these solitons wg these tools. ‘ ace else 45 le Sample run of above program is as shown below 1) enter number 1: 2 | enter number 2:3 | enter number 3: 4 numbers are 23.4 | Sum of three given nunbers is 9 || Sun oF non-duplicate nunbers is 9 | Enter nunber 1 : 3 Enter nunber 2: 2 Enter number 3:3 hurbers are 323, Sun of three given nunbers 15 8 Sum of non-duplicate numbers is 2 | Enter nunber a: 4 | Enter number 2; 4 | Enter number 3: 4 Numbers are 444 Sum of three given numbers is 32 Sun of non-duplicate numbers is 0 YY 4: CONDITIONAL AND ITERATIVE StaTeiyenrg 4 Program 10 test the divisibitiy o another number (i.e. if a ny 1 a number with Sa, ‘another number) imber Is divisible by a at the Program ™ below ; Pose, | 1 . that ruera = Ant input "Enter First usher ge Erker Frat mnt lou runber2.= int(input(“Enter second norte 2) 19.0 fs nee ntti “sing revainder = number % nunber2 ) J ere NE BY 3.0 aim ifremainder ==@ : | Ener first miner + 9 print (number, "is divisible by« er second number : 17 ise! fe by", nunber2) 119.0 is divisible by 17.0 See | | print (numberd, "is not divisible by", nunber2) i Enter First nurber = 1234.30 Enter second nusber : 5.5 ; 12H.3 is not divisible by 5.5 p Program to find the muhiples of print("Enter five numbers belox") rum = float (input ("First nunber :*)) num2 = Float (input ("Second nunber :")) nun3 = float (input (“Third number :*)) nud = float (input ("Fourth nunber :")) numS = float (input ("Fifth nunber :")) divisor = float (input ("Enter divisor number :")) count = 0 print ("Multiples of", divisor, “are :") remainder = nui % divisor if remainder ==@: a number (the divisor) out of given five numbers. print(numi, sep="") count +=1 remainder = nun2 % divisor if remainder is 9 print (nun2, sep="") sis? count += 1 remainder = num3 % divisor sample run ofthe program if remainder == 0 : is as shown below = prine(nuns, sep ="") | enter five numbers below net First number : 185 is 8 tenainder Second munbe Pl i Af remainder third number a print(num4, sep="") } Fourth — 7 Pil Fifth number ? count += 2 ber per 2 15 remainder = numS % divisor enter “ es Tare t Af remainder == @ + multiples: if 4 a") 3450.0 — J multiples of 25.0 found is 22 count4=2 . 5 is? print() divisor, “found ? print(count, "multiples of" COMPUTER SCIENCE WITH Pity, for clearing oreo of circle oF perimeter of ice. ‘menu for cateulat 4.6 Program ro dis an je: radius « Float ( input (“Enter radius of the circ rrorem print (1, Calculate Area") . print (*2. Calculate Perimeter’ ) choice = int (Anput( “Enter your choice if choice == 15 area = 3.14159 * radius * radius print ("Area of circle with radius” (10r2) 7) radius, ‘As’, area) else: perm =2*3,14159 * radius . «te, per print ("Perireter of circle with radius", radius, ‘is’, perm) ‘Two sample runs of above program is as shown below 1, calculate area 2. calculate rerireter Enter your choice (ler 2): 1 area of circle with radius 2.5 is 19,6349375, RESTART Enter radius of the circle : 2.5 | 1. cateutate area f Enter radius of the circle : 2.5 | 2. Calculate Perimeter | Enter your choice (1 or 2) 2 2 [Perimeter of circle with radius 2.5 4s 15.70795 Notice, the dition of f statement can be any relational expression or a logical statemet (ie, a statement that results into either true or flse). The if statement is a compound statemet hence its both if and else lines must end in a colon and statements part of it must be inden below it 4.5.3 The if . elif Stotement Sometimes, you need to check, another condition in case the test-condition of Thatiis, you want to check a condition when control te, form of else if. To understand this, consider this Hates tofée aches else part, ie, condition test int sample : Af runs are pore than 100 | then st is a century else if runs are nore than 50 | then st isa fifty else batsman has neither scored a century nor fifty Refer to program 43 given earlier, inside another iffel: To serve conditions as above if insi 1 Python priest Fase endo " elseif form (or if inside an else), Python provides i-elf = where we have used h ment ment, ented falst- e gard y 4: CONDITIONAL AND ITERATIVE STATEMENTS ‘The general form of these statements ig: if + x - ctotenene n> |eSpound stern [statenents) and if = 100: print ("Batsman scored a centu elif runs >= 50: — This Mock il be ce te bth he print (“Batsman scored a fifty") ifscondiion (ie, runs >=100 ) and elif foniton (1 ene =80 ) oe fae, else: <———— # print ("Batsman has neither scored a century nor fifty") Python ail txt this eoaton in case presous condition (mans >= 100) fale Let us have a look at some more code examples : if num <@: print (num, "is a negative nurber.") elif num==@: a print (num, "is equal to zero.") else: os print (num, "is a positive nunber.”) don’t get angry. I was just kidding. ve y above code is doing ? Hey, i fanzou mae out wn gb ete i aie (= 0) oF 20 (=0) or Positive (> 0), Consider another code ‘example : Af sales >= 30000: discount = sales * 8.18 elif sales >= 20000: discount = sales * 0.15 he con be as many Mel 308 ent euitsates >= 10000 | | CQ tn este trnn to en = sales Tit i hn nef s les * 8.05 above condition discount = 52 COMPUTER SCIENCE WITH PYTHON Jif statement. der following program that uses 2° if-el ssacemuis il bers and an arichmettc ‘operator and displays am ds two nurnbe' Program that read tt una « Float (np soon wus = float ( input( “enter second ni op = Anput( “Enter opera result =0 ifopse't = result = nur + nun itor [+-" elif op= result =nunt- nun2 elif op result elif op=='7": result = num / nun2 elif op ==" result = nun nun2 else: print ("Invalid operator! !*) result) num * qum2 print (num, op, nun2 Some sample runs of above program are being given below : Enter first nusber : Enter second number Enter operator [+-* /%] : 5.0 * 2.0 = 10.0 Seemcnsteerewnsceeses RESTART sooeeenneneeeneeccennnne 2 Enter First nunber Enter second nunber Enter operator [ + 5.0/2.0=2.5 Enter First number Enter second nunber Enter operator [ + - 5.0% 2.0=1.0 RESTART eee 2 (81i% Now try writing code of program 4:3 using if clif-else stat | 4.5.4 The nested if Statement ementa, 4 econditional expression» : | statement (s) else: statenent(s) elif : Form 2 ( if inside eli's body ) statement, [statements] el4f : 4 : statement(s) else: statenent(s) else: statenent [staterents] Form 4 | if inside if’s os well as else’s or elif’s body, i.e., multiple ifs inside ) Af = else: 4 ceonditional expression» : Af «conditional expression? ; statement (s) . | statenent(s) else: alse: statenent(s) statenent(s) else: 44 ="A' and ch <= Sample run of the program is as shown print (“You entered an Upper case character.") below elif ch>=' print ("You entered a lower case character, and ch¢e'z _ Enter a character You entered a digit. . . Sencommccnss RESTART examen elif ch >= "8" and ch) delta=b*b-4%atc ath sqrt() if delta>o: To use this function, add first line as. Import math to your program root1 = (-b+math.sqrt(delta)) /(2%a) root2 = (-b-math.sqrt(delta)) / (2* a) print ("Roots are REAL and UNEQUAL") print ("Root =", root, *, Root2 elif delta==0: rooti=-b/(2"3); print ("Roots are REAL and EQUAL") = print ("Rooti =", root1, ", Root2 =", rootl) An [statement is also known a5 else: a conditional, print (“Roots are COMPLEX and IMAGINARY") a a root2) For quadratic equation, ax**2 + bx + c = 0, enter coefficients below \ enter a: 3 ij enter b : 5 | enter c : 2 Roots are REAL and UNEQUAL | Root] = -0.666666666667 , Root? = -1.0 () weeszaccccecsnescocnsece RESTART suassuausnasaesecessseresrees | For quadratic equation, ax**2 + bx + C= 0, enter coefficients below | Enter a: 2 | Enter b : 3 Enter c: 4 Roots are COMPLEX and THAGINARY | weeeeeeceessaeeemeemessos RESTART ===8=smasasnansseesesssanaaae For quadratic equation, ax**2 + bx + ¢ = 0, enter coefficients below Enter a: 2 \ Enter bz 4 Enter cz 2 Roots are REAL and EQUAL © Rooth = -1, Root? = ~ 142 Storing Conditions Sometimes the conditions your program more readable, you can use name and then use that named conditional ditions similar to the ones given below + For example, to create cor © Ifa dep: © Ifa deposit is ®2000 or more 7 percent. © Ifa deposit is more than R60, © On all deposits for 5 years or more, Noe 42 4. 5 What is a selection statement? Which selection statements does Python provide ? How does a conditional expression affect the result of if statement? Correct the following code fragmer Af (x2) k= 100 else k=10 What will be the output of following code fragment if the input givem is (7) 7 (it) 52 input (‘Enter a nucber’) Af (a =e5) 5 print (Five" ) else: print (tot Five") What will be the output of the following code fragment if the input given is (i) 2000 (i) 1900 (itt) 1971 ? year = int(Snput( “Enter 4-dsgit year") 4¢ (year % 100 == 6) 4 (year X 400 == 0): print CLEAP century year") else: print (Wot century year") What will be the output of the following “ code fragment if the input given is (i) 2000 (Gi) 1900 (iit) 1991 ? year = int(input( “Enter 4-digit year")) 4 (year % 100 =~ 0) ¢ AF (year % 600 == 0): print ("LEAP century year") else print (Wot century year") being used in code are complex is less than £2000 and for 2 or more years, put less than 26000 and for 2or more years the interest rag, 100 and is for I year or more, the interest is 8 percent, COMPUTER SCIENCE WITH Princ, m and repetitive. In such cases, ty named conditions ie., you can store condi 1 in the if statements. vi the interest rate is 5 perceny, interest is 10 percent compounded annually, ‘The traditional way of writing code will be: if deposit < 2000 and time >= 2 : rate = 8.05 But if you name the conditions separately and use they later in your code, it adds to readability and unde, standability of your code, ¢-., elighble_for_5_percent = deposit < 2000 and tine >= 2 eligible for_7_percent = 2000 c= deposit < 6O8@ and tire cligible_for_8_percent = deposit > 6020 and tine >= 1. eligible fer_10_percent = tire >= 5 Now you can use these named conditionals in the codeas follows : Af eligible for_s_percent : rate =@.05 elif eligible for_7_percent + rate = 0.875 You can use named conditions Inf statements to enhance readabit and reusability of conditions. _ DEcIsION CONSTRUCT if Progress In Python 4.1 This ‘Progress in Python’ session is aimed at laying string foundation of decision constructs. portrcee, CONDITIONAL AND ITERATIVE STATEMENTS ggperiTION OF TASKS — A NECESSITY 6 7 i c 7 4! we mentioned earlier that there are many situations wh jn and again ¢g., the tasks of making. chapatis/dosa: ee Wr if you have to write pseudocode for this task ho est write the ere You need to repeat same set of tasks s/appam at home, as mentioned earlier. > Ww Would you do that. et us fi task of making dosas/appam from a prepared batter. Heat flat parvtawa Spread evenly the dosa/appam batter on the heated flat pan. Flip it carefully after some seconds, , Flip it again after some seconds. Take it off from pan. To make next dosa/appam go to step 2 again. aerene Let us try to write pseudocode for above task of making dosas/appam as many as you want. sprerequisites : Prepared batter Heat flat-pan/tawa Spread batter on flat pan Flip the dosa/appam after 20 seconds Flip the dosa/appan after 28 seconds Take it off from pan if you want more dosas then 277? else stop Now what should you write at the place of 2272, so that it starts repeating the process again from second step ? Since there is no number associated with steps, how can one tell from where torepeat ? | There is a way out : If there is a label that marks the statement from where you want to repeat the task, then we may send the control to that label and then that statement onwards, statements get repeated. That is, Fevdocode Reference 1 #Prerequisites : prepared batter Heat flat-pan 7 Sread ; Spread batter on flat pan Yom et gens is of Flip the dosa/appam after 20 seconds ¥ Sons Flip the dosa/appan after 20 seconds . Take it off from pan If youwant more dosas then - Go to Spread ¥ Else Stop END 1Doted arrows show hose the control flows {from one statertent to another] hi COMPUTER SCIENCE WITH PYTHON « y you want. But wha; s/appam as you want ig losas/apPiabove pseudocode will ma i king as many d Now the above pseudocode is fit for me ypam ? In that cas you already know that you need only eee is, we need to maintain a count of tat it i pseudocode for this situation. For this, we BES ‘sf Let us try to write pseu dosw/appam made, Pseudocode Reference 2 Prerequisite ; prepared batter i AL Heat flat pan a Initialize count too v v- . Spread: Spread batter cn flat pan 3 Flip the dosa/appan after 20 seconds . ft E Flip the dosa/appan after 20 seconds Fe Take it off from pan v G Addi to count ! 4. Tf cout ==6 then ¥ \ stop I r else i Sotospread fom oncsatene tome { 2. nd If we number the pseudocode statements as A.B.C.... as shown above for our reference, if you notice carefully, the statements are executed as A 8 CDEFGHT CDEFGHI COEFGHI Rs .eHsap Ls Siatemants repeated CDEFGHI CDEFGHI cDEF , CDEFGHT COEF GHY DEFGHE 2. You can see that statements C to are repeated 6 times or we can Say that loop repeated 6 times. This way we can develop logic for carryi i oF carrying out repetitive tasks, either based tion (oseulocoe reference 1) ora given number of times (pseudacore reference 2). ons cons To carry out repetitive tasks, Python doe: f following iterativeflooping statements : | © Conditional loop white (condition based loop) © Counting lop for (loop for a given number of times), Snot have any go to sletentent rather it provides ‘et us learn to write code for repetitive tasks, in Pythor J n rage The functio corre 1 pase 4 CONDITIONAL AND ITERATIVE STATEMENTS 1 47 THE range( ) FUNCTION peor ert vith Loops, recall fe ty of Python, let us discuss the range() function of thon, which w 'ython for loop. The range ( ) function of Python generates a list which is : special Sequence type. A sequence in Python is a succession of values bound together bya single name, Some Python sequence types are : strings, lists, tuples ete. (see Fig. 4.6). There are some advance sequence types also but those are beyond the scope of our discussion. tise [5, 7, 8, 22) fio eee 2 45 C7 Aus ib ite pee rl, ~ ae nd 2d ee Astring \ single rae, . igure 4.6 Some commen sequence types Let uss e how range( ) function works. The common use of range( is in the form given below : range( , ) al values should be Antegers COMPUTER SCIENCE WITH PYTHON That is, funtion gers #3, vand sore ster range(1 Us 5) esi wel produce a ist having values as L814 25 ea wep 12 rrange(®, 10, 2) 4 pe = will produce list as { 0, 2,4, 6,8] eet "A sent n Pro a - epee succession of values boy range (5, 0, -2) m1 together by a single name eg will produce list as [5, 4,3, 2,1. fst tuple, string, The range) ns a sequence of Ist pe, Another form of range) is ange () consider following raget ) function: i that creates,a list from 0 (zero) to — 1, &8-r range(S) The above function will proctuce list as [0, 1, 2, 3, 4]. Consider some more examples of range) " function : aan Values generated , 4 sange0) 0.1.235567,89 15 RATION | range(S, 10) 5,6,7,8,9 Teeiteratic | ranget3, 7 34.5.6 ceately range(S, 15,3) 581,14 Ioeping st i range(9, 3,-1) 9,8,7,6,5,4 tegores, range, 3-2) 10.86.42 tan cv Operators in ond not in | Lat us also take about in operator, which i used with range) in for loops. © cond Tocheck whether a value is contained inside alist you can use in operator, ¢. y eB 3 $n [1,2,3,4] qannenene Tht exes vil et ratue 5 l eontainal i the gine sequence ‘ilretur Treas value3 is contained in sequence, 2,3, 4 oasam “al r 5 4n (1,2,3,4) The In operator tests if gh" | will retum False as value is value is contained in a sequer® 34) But 5S isnot contained in sequence [1, 2, Or not and returns True o Fat { accordingly, : 5 not dn [1,2,3,4] a will retum True lue 5 is . Perator, "ot Contained in sequence {1, 2, 3,4} ™ id not in are the Sequence. Thus, in and not in are alen mn {Pat check for membership of a value inside? | Yi, ‘bership operators. These operators work wit Nee, “ anf SSqUERCE YES strings, tunes and dee et Cchoptee 4 : CONDITIONAL AND ITERATIVE STATEMENTS 147 For example, consider following code : ain “trade” will return True as ‘a’ is contained in sequence (string type) "trade’ cash" in “trash” will also return True for the same reason. = Now consider the following code that uses the in operator : (Operators in and not in are also % hat uses the in operator : ees ; } sas penned Line = input( “Enter a Line :* ) string = input( “Enter a string :") : Ifthe given string lpn of Tine if string inline; <———_ print (string, “is part of", Line.) else: print (string, “is not contained in’, Line.) You can easily make out what the above code is doing - it is checking whether a string is contained in a line or not. Now that you are familiar with range( ) funetion and in operator, we can start with Looping (iteration) statements, 4.8 ITERATION/LOOPING STATEMENTS The iteration statements or repetition statements allow a set of instructions to be performed repeatedly until a certain condition is fulfilled. The iteration statements are also called foops or looping statements. Python provides tuo kinds of loops : for loop and thile laop to represent tro categories of loops, which ar © counting loops the loops that repeat a certain number of times ; Python's for loop is a counting loop. © conditional loops the loops that repeat until a certain thing happens ie, they keep repeating as long as some condition is true ; Python's while loop is conditional loop. 4.8.1 The for Loop “The for loop of Python is designed to process the items of any sequence, such asa list ora string, one by one. The general form of for loop is as given below + This determines how ruany time the loop veil got repeated. for in Colon is mast here statements_to_repeat tan om ere the statements ta be repeated will be placed (body-of:the-loop) For example, consider the following loop = The lap riche a, Variable Zoe, Sodetnitybrecirae frase [ 4712 1s se a of the for ap A sent ‘ssf the fo tinea Pht print (a) In the Bay ofthe oop wil be execute for each wen print(a* a) reac ep ria Le ey fr mt A for loop in Python is processed a5# © The loop-variable is assigned tm ‘ 5 all the stotementsin the body 0 Giep?) riable is assigned the ee ? a COMPUTER SCIENCE WITH THON.» we {in the sequence- 1 af fest value in Oe gith assigned Wal OF TOOP Vari 3 Joop are exer 4 (aaa e eo 1, the loop a the once step 2 is over: id the loop-body Batata ter talk , | Pent value in the, see) th the new value of Ses ee | executed (Fe, step 2 9 ine Joop-variable. enon, ; Th Pein ae until all values in the sequences $F wt © This continu vel processed. - ° | forain [14> wt i : ‘That is, the given for loop will be antag ; processed as follows: POG ‘ (0 firstly, the loop-variable a will ‘ be assigned first value of Tist ie, Land the statements in the body of the loop will be executed with this value of « j Hence value 1 will be printed with statement print(a) and y value 1 will again be printed |! with print(ata). (see execution ‘at stotom out right) (i) Next, a will be assigned next value in the list ie. 4 and loop- body executed. Thus 4 (as result of print(a)) and 16 (as result of print(a*a)) are printed. (iil) Next, a will be assigned next value in the list ie,, 7 and loop- body exceuted. Thus 7 (as result of print(a)) and 49 (as result of print(a*a)) are printed, (iv) All the values in the list are ! executed, hence loop ends, Therefore, the output produced by above for loop will be : =i Y assigned first value and with ‘this value, 211 statements in ‘oop body are executed ina print (1) print (141) a “ ana a assigned next value and oop body executed with a as 4: print (4) print (44 prints iid a7 assigned next value and loop body executed with a as 7 print (7) print (797) .. prints Nomore values LED MF >i a) CChopter 4 : CONDITIONAL AND ITERATIVE STATEMENTS Consider another for loop : for chin'calat : print (ch) (0 forloop ends when the loop is i ‘repeated forthe ast value of the | ‘The above loop will produce output as : ‘sequence. i c 01 The for loop repeats a . ‘number of times, where ns the | 1 : ‘length of sequence glen in for-loop's header. 1 " ieee (variable ch given values as‘c’, "'Y, ‘m’ — one at a time from string ‘calmy’.) Here is another for loop that prints the square of each value in the list : for vin [1, 2,3]: print (v#v tv) The above loop will produce output as : 1 8 81 ‘The for loop works with other sequence types such as tuples also, but we'll stick here mostly to lists to process a sequence of numbers through for loops, As long as the list contains small number of elements, you can write the list in the for loop directly as we have done in all above examples. But what if we have to iterate through a very large list such as containing natural numbers between 1 - 100? Writing such a big list is neither easy nor good on readability. Then ? Then what ? © Arey, our very own raiget ) function is there to rescue. Why worry? ;) For big number based lists, you can specify rangef ) function to represent a list as in for val in range(3, 18) t print (val) In the above loop, range(3, 18) will first generate a list [3, 4,5, .., 16,17] with which for loop will work. Isn't that easy and simple? © You need not define loop variable (val abo code example that uses range( ) function in a P 4.11 Program to print table of a number, say 5. above) before-hand in a for loop. Now consider following, for foop to print the table of a number. num = 5 | sxiss for ain range(1, 11) = | 5x2"10 print (num, '¢, a ‘=', num* a) | Sx3015 | 5x4=20 The above code will print the output as shown here + | 5x5=25 | 5x6 = 30 a= ) sx7n 5x B= 40 ‘You need not pre-define loop Sx9= 45 5 x10 = 50 rate o for oop, COMPUTER SCIENCE WITH PYTHON - ine the sum progressively, Le, of 7. Pel sum of acura} numbers BECwee? 110 - . re $612 reagan ember, ri 3 smo for ninrange(2, 8: t ane Co gat, “18> sum) print ("Sum of natural nuabers ‘The output produced by above program will be + sum of natural numbers <= 145 1 sun of natural nunbers <« 2 is 3 sun of natural nunbers <= 3 1s 6 sun of natural numbers <= 4 is 10 Sum of natura? numbers <= 5 is 15 ‘Sum of natural numbers <= 6 is 21 | sun of natural numbers <7 is 28 : PS 4.13 Program to print sum of natural numbers between 1 10 7. | » sun=0 forninrange(1, 8) : sun4=n 9 print ("Sun of natural numbers <=", n,'is*, sum) The output produced by above program is : {sum of natural numbers <= 7 is 28 Carefully look at above program, It again emphasizes that ————= body of the loop is defined through indentation and one more fact and important one too ~ the value of loop variable after the The loop varlable contains the {for loop is over, is the highest unlue of the list. Notice, the above highest value of the lst after the loop printed value of 1 after for loop as 7, which is the Peaic b ever. Program 438; highlights this fact. maximum value of the list generated by range(1, 8). : 4.8.2 The while Loop A while loop is a conditional loo i ru ns withi sel as hi p that will repeat the i ions within i ; conditional remains true (Boolean True or truth value tite , Me seas loge teat { The general form of Python while loop is : while 0": Excerpt aa, he oon print (*hel26%, a) eal oun upto cv a ogo ‘condition i eve asan3 ‘The foop ets wen the conlton eates to false print ("Loop Over! 1") The above code will print : netto SDs ert fot pete 2 (sop overt hha tc “ter the white toop. Let us see how a while loop is whltea>o: processed: + print (“hello™, a) 4. a=0-3 Sep 1 The logical/conditional expression in the while loop (eg, a> above) _[ahas value § before entering into while loop] is evaluated. \ (0 wnile’s condition tested with a's current value as 5 2.Case if the result of step 1 is 5 >0 =True \ \ true (True oF trite yy) hence loop's body will get executed | then all statements” in print (*hello", 5) » ellos the loop’s body are a =5-3=2. (abecones 2now) MS | executed, (see section (9) & (ii) on the righ) Case Hl if the result of sicp 1 is (i) while‘s condition testedwith a's current values 2 2>0 =True ‘ false (False or false pi) then control moves to loop body will get executed the next statement after print "hello", 2) sriay heldo2 the body-of the loop iz. ja 223004 (0 beconessionh loop ends. (see section (iif) on the right) (ii) while's condition tested with a's current value~2 Step 3 Body-of-the loop gets executed. “1 > @=False This step comes only if Step 2, Loop body will not get executed Case J executed, i.¢., the result of control passes tonext statement: logical expression was true. This after while loop 5 step will execute two statements of loop body. After executing the statements of loop-body again, Step 1, Step 2 and Step 3 are repeated as long as the condition remains true. The loop will end only when the logical expression evaluates to false. (ie, Step 2, Case Iis executed.) COMPUTER SCIENCE WITH, [The varlable used Consider another example = ‘condition of while have some value not entering Into while loop, whilen<5t ees nstist atm) Soro print ("square of "s M+ nved hank YoI srorerent snot port of ie oop body — OT Cf print ("Tt ‘The above code will print output as: se ora isd u are because of te tare of ito Ta ne et executed 4 times) sere EE NEg |< bapldrenn fcr ae Square of 34 square of 4 is 16 le tion n< 5 is trie above, the while ‘s y ecw loop is exccuted that prints Thank You. Anotomy of o while Loop (Loop Control Elements) ; Every while loop has its elements that control and govern its execution. A while loop has jar elements that have different purposes. These elements are as given below : 1. Initialization Expression(s) Gtarting) Before entering in a white loop, its loop variable must be initialized. The initialization of thelaep variable (or control variable) takes place under initialization expression(s). The initialization expression(s) give(s) the loop variable(s) theit first value(s). The initialization expression(s) f I a wehile loop are outside the while loop before it starts, | 2. Test Expression Repeating or Stopping) The test expression is an expression whose truth value decides whether the loop-body wile executed of not. If the test expression evaluates to true the loop-body gets exceuted, others the loop is terminated. " Ina while loop, the test-expression is evaluated before entering into a loop. 3. The Body-of-the-Loop Doing) The statements that are executed vi 66 repeatedly (as long.as the test-expression is tre) form the Ina wl very iterati | imipeenci e gen iteration the test-expression is evaluated and if it is rue, the testexpression evaluates to false, the loop is terminated: 4. Update Expression(s) Changing) The update expressions change th; Statement inside the body of eh eon f°? while loop. anable: The update expression is given 35+ the hail fthele} Chapter 4 : CONDITIONAL AND ITERATIVE STATEMENTS. Consider the following code that highlights these clements of a title loop : raiolization expression: —__» ne Mates loop vane n=16 Test expression : based on this coruiden, ini : , loop iterates fe. repeats whilen>@: dy of the top ———.. print (n) ins indented statements Update expression: changing vole [Seath witey nae3 aap ate pennies Other important things that you need to know related to while loop are : © Ina white loop, a loop control variable should be initialized before the loop begins as an uninitialized variable cannot be used in an expression. Consider following code : 8 A ais itt ra is ll elt nero if variable p has while p rove ne od © The loop variable must be updated inside the boly-f the-while in a way thot after some time the test-condition becomes false otherwise the loop will become an endless loop or infinite loop. Consider following cod aes wate a> 0 ¢-+————— ENDLESS L007! Bas te pba remains Saree outa to upe in the tpl, print (a) faerie ee print ("Thank You") ‘The above loop is an endless loop as the value of loop-variable « is not being updated inside Joop body, hence it always remains 5 and the loop-condition @> 0 always remains true, ‘The corrected form of above loop will be : ass while a>: Loop variable a being updated print (a) a ie te oo tos a-s1 print ("Thank You") We will talk about infinite loops once again after the break statement is discussed. Since in a while loop, the control in the form of condition-check isat the entry of the loop (loop isnot entered, if the condition i is false), it is an example of an entry-contrlied Toop AR he suming af 30 entry-controlted loop isa loop that controls the entry in the loop eee er cn, pet by testing a condition. Python does not offer any ‘Contec keys anytime during Its exit-controtled loop. s= seenten 3 309 ae Now that you are familiar with while loop, let us write some programs that make se of while looP- _ ————— “COMPUTER SCIENCE WITH PYTHON . ca murabers 4.14 Program ro cotctate te fctora! of er a numbel num » Ant ( input (“Ents ™» fact et 1 aed ' hte a cx nut a fact = fact*® 1 facta gaeatl ' print (the Factorial of, num, “is, F8Ct) below Sample nuns of above program are given enter a nunber : 3 The factorial of 3 is 6 eweenccscnncecemnernen RESTART enema enter a number : 4 The factorial of 4 is 24 ae K P 4.15 Prograrn to celculate and print the sums of even and odd integers of the first natural numbers. ogra ™ n= int(input( “up towhich natural number ?" )) ctre2 ‘sum_even = sum_odd = 8 while ctr <=n: ifctr%2e20: number is even sun_even += ctr 1 else: sun_odd += ctr etre #increnent the counter print ("The sum of even integers is , sun_even) print ("The sum of odd integers is", sum odd) ‘The output produced by above code is |) up to which natural nurber? 25 |) The sum of even integers is 156 | The sum of odd integers is 169 4.8.3 Loop else Statement Both loops of Python (je, forloo i ° i, p and while Io. f else of if-else statements, The else of a loop esate only only when the loop is ending because the while loop's we Ise clause, which is different from seas hen the loop ends normally (t+ cop's test condition has resulted in false or the hope 4 CONDITIONAL AND ITERATWE Staventnns {for loop has executed for the last y Jeam in the next section that ita etkstatementisreached in [CREE e 7 tent is reach, the loop, while loop is terminated Pre-maturely even ithe test-condition is still true or all values of seq ‘ h ‘The else cause, ‘of aPython loop a uence have not ‘exteutes when been used in a for loop, : a [ee ety mae the lop i teminatng beens clse clause it cha bret ania atements. Thus = vent and then we'll get back ain With examples, 4.8.4 Jump Statements — break and continue [Norma Python offers two jump st In order to fully understand the will be useful to know the working of bros sy let us first talk about break statem to lovprelse clause ag, working of logy 'tements to be used within loops to A reoktalement sins the est ump out of loopviterations, These are broil and eeepe? ina nosten eee statements, Let us sew how these slatemente wosk, "< oy loop. 4.844 The break Statement The break st terminates enables a program to ship over a part of the the very loop it lies within, Execution resume: following the body of ‘ment. The following figure (Fig. 4.7) explains the code. A break statement at the statement immediately © terminated stat working of a break statement : while : for evar> in sequencer : | statenent 1 statenent 1 Statements 4 the if : Af ceondition> : fist statement wher break break Be boop staterent 2 staterent 2 statenent 3 , staterent 3 100: fof the Inop so that loop can be break terminated. jump statement like the break statement as both the le. But the continue statement is somewhat different from temient forces the next iteration of Uke loop to The continue statement is another statements skip over a part of the cod break. Instead of forcing termination, the continue sta take place. skipping any code in between COMPUTER SCIENCE WITH PYTHON inue statement | rorking of continue igure (Fig, 48) explains Pe working, | ee rp in : for «va : ihe tn ‘staterent 2 | f aaite tertconeition 2) set htt ne | iPecaie i Spped al nest coal | | ie copateton sel = : | ses statenent 3 j staterent 2 = Stateeent 3 wea ’ statezent 4 as Tipping oso 2 eh fraton wl 03 | aor ope cas wea Ia Pere ron an ‘The working ofa continue statement. figue 48 For the for lop, continue causes the next iteration BY updating aaa the loop variable with the next value is sequence j andl for Fai evinas dete) avvitonal test {AEs faz te oop Sand hile loop, the program control passes to the and causes the next iterat given at the top of the loop. 4 couse: oat the loop totake place. | a=becHe for 4 in range(®, 3) + print ("Enter 2 nunbers” ) a = Ant (Anput( “Wunber 2 :* )) bent (input ("Number 2 :")) if print (*\n The denominator cannot be zero. Enter again |") continue else: cra/b print ("Quotient =", c) Sample run of above code is shown below Enter 2 nunbers Nunber 1: 5 nurber 2: 0 tee mane etnee 1 At this point continue forced net iteration vo take place. ‘The denominator cannot be zero. Enter again | Enter 2 numbers Nunber 1: 5 Number 2: 2 Quotient = 2 Enter 2 nunbers Nunber 1: 6 Number 2: 2 Quotient = 3 Chepter 4 : CONDITIONAL AND ITERATIVE STATEMENTS nee Sometimes you need to abandon iteration ofa loop Prematurely. Both the statements break and continue can help in that bul in diferent situations statement break teen ee all pending eee ee eed ane continue to terminate just the curent iteration lave wil Cone with rest of the iterations, ie iteration, loop Following program illustrates the difference in working of break and cowtinue statements. ANT Program to ittustete the difference berween break and contioue statements, P. 7 Print ("The loop with’ break" for § in range (1,11) ; if i%3 00: break else: print (4) produces output as Print ("The loop with’ continue’ produces output as for { in range (2,11; if 1x3 <0; continue else print (1) ‘The output produced by above program is: The Toop with break’ produces output as + 1 F because the loop terminate with tral The Toop with * continue * produces output 95» H 2 4 fonty the values divine by 3 une missing 0s the loop ‘ ee tiie Though, continue is one prominent jump statement, however, experts discourage its use whenever possible. Rather, code can be made more comprehensible by the appropriate use of iffelse. 4.8.5 Loop else Statement Now that you know how break statement works, we can now talk about loop-else clause in details. As mentioned earlier, the ese clanse ofa Python loop executes when the loop terminates ormally, i, when testcondition results into fase fora wife loop or for loop has executed for the last value in the sequence ; no! wen the break statement terminates the loop. Before we proceed, have a look at the syntax of Python loops along with efse clauses. Notice that the else clause of a loop appears at the same indentation as that of loop keyword while or for. COMPUTER SCIENCE WITH PYTHON, with else clause is.as given below Complete syntax of Python loops aon “ee » st condition? : : while in «sequence? = statement Se statement2 statenent ° aa else: ‘ statement(s) statement(s) Following figure (Fig. 4.9) illustrates the difference in working of these loops in the absence ang presence of loop else clauses. rt i For celenent> in crequence> FE next element } while in Sone 2 Lange STE FEmSnE -- eo | seee3]| sm seatenent 5) Dla statement. tat Statenent sate seater wo |. : getpae|---7] sateren 1" ‘sulla rement statement suite ‘ i | 1 ‘Siterets { seen + oat eas > sinners __f statennt staterent: : outside the fogp —> D> : statenent {b) Control fow In Python locps in the presence of loop-else cla use, } Figure 4.9 Working of Pytho i 3 n Loops with or without else clauses, Chopier 4 + CONDITIONAL AND HeRATIVE stareMenIS Let us understand the w orking of the without else clause with Python it The help of e282 Loops with or ‘ode examples, fora inrange (1, 4): print ("Element is", end = In the case of normal print (a) [termination of loop. eee else : print ( “Ending loop after printing ala elements of sequence") The above will give the following output : The utp produc by for bop. Notice for toup executed Element is 1 Tis ln i priv becase the ese clause of pric rauesofa1.2°3—~s] Etomene 4s 9 enfant tthe frp Elenent is 3 Ending loop after printing a11 elenents of sequence. Now consider the same loop as above but with a break statement : fora inrange (1, 4) : Hakaeco; ett si erate break print ("Element is", end =*') print (a) else: print ("Ending loop after printing all clenents of sequence”) Now the output is Nuri that for a = 2, the break got xccuted and lp terminated Lines cog prin tara = 1) As break terminate the oop, the else clause obi dil not erate, Elenent 82 5010 lve afc te printing of eles The else clause works identically in while loop, fc, executes if the test-condition goes false and Not in case of break statement’s execution. Now try predicting output for following code, which is similar to above code but order of some statements have changed. Carefully notice the po for ain range (2, 4) : print ("Element is", end=' ') print (a) Afax2 break ann (“Ending loop after printing all elements of sequence") i loop-else suite. The else in above Yor i you are. @ This code does not have 7 , coteispat ‘fee roll tooplse Now consider following program that uses else clause with @ While loop. computen SCIENCE MATH PYTHON ayram ens when the users int sheur sum" The ie 4.18 Progra ee repeat os ‘sen the number en" od 15 less thon rer, " . mat termination) oF PF mm ? arom ent (yormal termination ’ ‘| wane count = sun =O ans’ : while ans ==" ” Bao the bn nun = int Anput ("Enter number = » = af nun <8 me print ("Number entered is below zero- Abort: ' break sum = sun ¢ nut count = count +1 . 1 ‘ans « input ("want to enter more numbers? (y/f)--") | toop-else suite ' = ” _— print ("You entered” , count, “norbers 5° far.")) print (Sunof nubers entered 18% SUB) py, ye ie ear 1 ; | enter number: 3 fant to enter nore nunbers? (y/n)-.¥ ! enter number: 4 1 xant to enter nore nunbers? (y/n)..¥ | Enter aunber + $ want to enter mare nunbers? (y/n)..n Res fei | you entered 3 nunbers so far. 4 orally sun of nuxbers entered is 12 RESTART 48 1se, Loop terminated Enter nunber : 2 want to enter more nunbers? (y/n)..y enter number : -3 Nunber entered is below zero. aborting! sum of nunbers entered is 2 No eweution of ferminatelixcause of break statement fase. boop 44, 4.19 Program to input a number und test if i is a prime number. rogam num Ant (input("Enter nunber :)) m= int(nun/2) +1 for 4 in range (2, 14m) = rem = num% i i if remus: print(nun, “is not a prime nunber” Enter number :7 break else: 7 is a prime number print(nun, “15 2 prine mmber) Enter nunber :49 49 is not a prime ™ te, ] Choptee 4; CONDITIONAL AND ITERATIVE STATEMENTS nat NI Sometimes the loop is not entered at all, re: r es the reason being empty it test-condition’s result as ftse before entering in the while loop. ko these eases, the oa a the loop is not executed but loop-clse clause will still be executed, * Consider following code examples illustrating the same, while (3>4): int (“in the Loop") <———__ Badly ofthe soup wit not be executed wise! ‘ oor") (ontliion is false) but lie clause will print (“exiting from while loop") The above code will print the result of execution of while loop’s else clause, ix., exiting from while loop Consider another loop — this time a for loop with empty sequence. fora inrange(10,1): print (“in the loop") <—— Beals of the foop wil nut be case. exweurel (empty sequence) : tut else clause usll print (“exiting from for loop") 0 | works n the same manner. That, Is, It gets executed when the loop Is terminating normally — | The above code will print the result of execution of for loop’s i else clause, i. after the last clement of o_ Sequence in for loop and when’ exiting from for loop Reese ‘ | 4.8.6 Nested Loops c terme A loop may contain another loop in its body. This form of a loop is called nested loop. But in a nested loop, the inner loop must terminate before the outer loop. The following is an example of a nested loop, where a for loop is nested within another for loop. for i in range(1, 6) : for jinrange (1,1): end = Vat the emt 10 cause ; get) 8) pring a same tine print ("*", end=' print () # to cause printing fromnext line. The output produced by above code is : The inner for loop is executed for each value of i, The variable i takes values 1, 2,3 and 4. The inner loop is executed once for i= according to sequence in inner loop range (i) (because fort 85 1, there is just one element 1 in range (1, 1) thus j iterates for one value, te, 1), twice for i=2 (vo elements in sequence range(2, i), thrice for i= 3 and four times for i= 4. gi While working with nested loops, you need to understand one thing and that is, the value of yf uter loop variable will change only after the inner loop is completely finished (or interrupted), - . a bes COMPUTER SCIENCE Winy Pm it ts ‘To understand this, consider the following code fragment 0 for outer in range (5, 10, 4) : for inner in range(1, outer, 2) = print (outer, inner) ‘The above code Will produce the output as : 51 53 J +——~ Te ouput produced when the outer =5 The ouput produced when the outer = 9 ) See the explanation below : 5 charge outer value — 9 change in outers value —__, 9 SS 9 9 43 loops ? What is the use of range() function ? J. What are iteration statements ? Name the iteration statements provided by Python. What are the two categories of Python What would range(3, 13) return ? What is the output of the following code fragment ? for a in “abcd What is the out code fragment ? print (a,°+', end» for 4 in range(o, 10) ; pass print (1) Why does for 4 in range(1@,1) + What ls the outpat of following code? print ("Hello") for a in range (2, 7) + for b in range(1, 9} print (8°, end = print ( ) ) put of the following “Hello” not print even once ? ) 1 3 inner nop got over after value 3's iteraton 1 3 — 7 ier loop got or ofier value 7's iteration Let us understand how the control moves ina nested loop. with the help of one more example : for a in range(3) : for b in range(5,7) : print (“for a=", a, "bnow is", b) The above nested loop will produce following output: fora=0 bnowis 5 fora=0 brow is 6 fora=1 bow is 5 pte) fora=1 b now is 6 fora=2 b now is 5 fora=2 b now is 6 Gas> Nowe, for euch oer st oP der lo eaten ee lg Cchapte For the outer loop, firstly a takes the value outer for’s loop-body. © fora=0, the inner loo; b=Sand b= © hence the fi © when a takes the next value in sequence, the inne! 5 and 6 for b. Thus we see, that for each iteration of outer loop, b=6. eS ers. 3 (contd) 8, Weite a for loop that displays the even runbers from 51 to 60. 9% Suggest a situation where an empty loop is useful, 10, What is the similarity and difference between for and while loop ? 11, Why is while loop called an entry contratled loop ? 12. If the test-expression of a while loop evaluates to false in the beginning of the loop, even before entering in to the loop (0) how many times is the loop executed? (8) how many times is the loop-else clause executed ? 1X. hat will be the output of following code: while (6 +2 > 8: print ("Gotchal") else: print ("Going out!") WA What is the output produced by following loop 2 for ain (2, 7): for b in (1, a) print (b, end =" *) print () What is the significance of break and ‘continue statements? B | 7% Gana tingle break statement in an inner! terminate all the nested loops ? 1 4: CONDITIONAL AND ITERATIVE STATEMENTS : P Will iterate twice for values two lines of output giv loop (a= 0 ; which involves tw 850 and for a=0, inner loop ilerates as it is part of t given above are produced for the first iteration of outer ‘0 iterations of inner loop) will again iterate two times with values inner loop iterates twice for values b=5 and Consider some more examples and try understanding theie functioning based an above Lines. fora inrange(3) : for b in range(5,7) : print ("*", en print () ‘The output produced would be : Consider another nested loop : fora in range(3) = for binrange(S,8) : print ("*", end="") + notice end =! 'at print () the end of priat ‘The output produced would be : The break Statement in o Nested Loop If the break statement appears in a nested loop, then it will terminate the very loop it is in. That is, if the break statement is inside the inner loop then it will terminate the inner loop only and the outer loop will continue as it as. If the break statement is in outer loop, then outer loop gets terminated. Since inner loop is part of outer loop's body it will also not execute just like other statement of outer loop's body. COMPUTER SCIENCE WITH PYTHON Ne 7 er loop only wig Following program illustea n the outer loop will progress as per its 5 25. prime numbers rom 35 through J will terminate the == tes this. Notice that breal rouline. > ED 4.20 Program thot searches (0 up is am for num in range(15,25)? F 4 ee (nan): gro determine factors Me num 1 ==: ‘ 4 je num/s , qum) € ‘This treo wil mint the / e¢, b") for", num : lene for top only print ("Found a factor pias not continue - factor found ve an me # else part of the inner loop sf se: print (nun, “is a prine number") o™ ; ie ! ‘The output produced by above program will be = es Found a factor( 3) for 15 7 Found a factor( 2} for 16 e \ 27 is a prime nurber o i Found a factor( 2 ) for 38 & ! 19 is a prime nurber A Found a factor( 2) for 20 ‘ { Found a factor( 3) for 21 : } Found a factor( 2) for 22 al | 23 is a prime number 4! Found a factor( 2) for 24 : \ \y More examples of nested loops and other simple loops you'll find in solved problems givenat . the end of this chapter. ‘This brings us to the end of this chapter. Let us quickly revise what we have leamt so far. Bay, ? PrtHoN Loops iP Progress In Python 42 | * This ‘Progress in Python’ session works on the objective of Python loops practi ice. Carefully read the instruction and then earry out the problem, Practice questions, you can move on to practicing programming Ong trough with conser) : problems, % Please check the practical com haan ponent-book — i G Science with Python and fill there a pa - Progress in Computer under Chapter 4 after puter. Practically doing it on the com i pordece Shy, N REVISE Ler Us 3 ge 4 # CONDITIONAL AND ITERATWE StaTeuents 167 4, Python statements cam be on one ofthese iypeg ss An empty statement is the statement that does 44 Single executable storement forms a simple = SPY Statement, single siatement and compound stotement othing, Pye ‘hon fers pass statement as empty stctement statement, 4 Some examples of compound statements ore % The flow of controt in a program con selection construct), and iteratively ‘T statement, while stotemert ete, be in three ways : 5 (the iteration construct), ‘equentially (the sequence construct), selectively (the 4% The sequence construct means statcments get exceuied sequentially, ‘& The selection construct rans the execution of stetrsens) depending upon oconlion test ‘% The iteration (looping) constructs mean repetition ofa set & Python provides one s depending upon o condition-test ection statement if fa many forms ~ if.etse and Lelif.else lent fests on expression ard depending upon its truth value one of the two sets-of-ection is % The if.else stavem executed. ‘The if-else statement can be nested also de., an if statement can he ‘% Asequence isa succession of values bound together by a single tuples. iave another if statement amie. Some Python sequences are strings, lists and ‘% The range( ) function generates @ sequence of Hist wpe. ‘% The statements that allow a sct of instructions tobe performed repectely are iteration statements. ‘% Python provides ewo looping constructs for onc! white. The for is courting loop and white is a conditional fop. ‘% The white loop is an entry-controlled loop os ft has @ contro! over entry inthe loop inthe form of est condition. ‘% Loops in Python can have else clause t00. The else clause ofa loop is executed inthe end ofthe loop only when Toop terminates normally. ; %, The break statement can terminate 0 loop immediately and the control passes over 10 the slatement following the statement containing break , ‘oppears in. ‘% In nested loops, « break terminates the very foop it appears % The coh stent abandons there iter fh bp by ning nth eof estes he loop-body. te immediately transfers control to the begtaning ofthe nex iteration of the loop. Solved Problems a ply statement 2 Wheat i ? What is the significance of au emply st / / Seaeen eee one copuerte eon art of aon anor seek tuations where the code requires a statement but logic does not. To multaneously, emply statement is used, Anempty statement is useful fill these two requirements me Python offers pass statement as an empty sta courte sce wt rion. | 8 a or moneterminat, eich label would you ging rminable If you are ashe t label the Python loops cas determinable _— udhich hay ? Justify wor ansieer Aled as determinable foop 3% number of 5 Herations can, = Ie aes {the sequence, It is operating Upon . se atte its number of iterations cannot, ble toop, as ‘cm wh sable ert of a test-condition, which cannery. Solution. Th determined beforehand as the over can be labelled as non-leter The ‘while loop’ can be labelled na determined beforhand, Iis iterations depend upon the determined beforehand. edinse? There are tow types of else clases in Python, What are these taro types of else Solution. The tu types of Python else clauses are: . (2) else in an if statement {t) else in a loop statemer se clause of an if statement when the condition of the if statement results int ise 1en the condition of the if stat tof The else clause of an if statement is exceuted when the _ last valuc in sequence, inating normally The else clause of a Loop is executed when the loop is terminating norma ') has gone false for a while loop or when the for loop has executed for the ing list (7, 3, -1, ~5} Use the Python ranget } function to create the foll Solution. : range (7, -6, ~4) Lentify and correct the problem with following code countdown = 10 # Count From 10 down to 2 While countdown > 8 : print (countdown, end = * *) countdown = 1 print ("Finally.") Solution. it is an infinite foop. The reason being, in the above while loop, there is an expression countdown ~1, which subtracts 1 from value of countdown BUT this statement is not updating bx !oop variable countdown, hence loop variable countdown always remains unchanged and hence is an infinite loop. The solution to above problem will be replacement of countdown ~1 with following statements the body of while loop : countdown = countdown = 3 Now the while loop's variable will be updated in ever eration and hence loop will be a finite loop. Following cade is meant to be an interactive grade calculation script for an entrance test that converts fret percentage into a letter grate: _— 90 and above is At, 20-99 1s A, 60-88 is A-, and everything below 1s fail (U know high standards), The program should prompt the user 100 times Sor grades. Uni fortunately, the program wens written bY lerrbl coder (ne), so there are numerous bugs inthe cate Find anne we sri teritten . ougs and fix them. For 4: range(1 .. 190) Grade #s Float (input( AF grade > 90 Print ("That's an A+ 1") “What's the grade percentage ?* » utio iat Solut Felon “0 Ghepler 4: CONDITIONAL AND ITERATIVE sTareMERTs 2 Af 80 > grade > 90: Print ("" "an A 4s py elsif 68 < grade : print (You got an A-1) else grade < 60: Print (Sorry, you need an Solution. The corrected code is given belo for 1 in range (@, 108) : grade = float (input( “what Af grade >= 99 : print ("That's an a+ 1 *) Af 80 <= grade < 99: print ("An A is really godt") elif 60 <= grade : print ("You got an A-! else grade < 69: Print ("Sorry, you need an A- to qualify!*) What is the output of following code ? Af (6+5 == 10): print (“TRUE”) else: print (“FALSE print ("TRUE") Solution. FALSE TRUE 8 Following code contains ant endless loop. Could you find out why ? Suggest a solution. cally good!" A: to qualify!") W, with corrections marked in colour. \s the grade percentage 2" )) # although triple-quoted string 4s also ok n=i0 answer = 1 while (n>) + answer = answer +n ** 2 nen¢] print (answer) Solution. For a while loop to terminate, it is ne But in the above code, the test-condition of rile is > Oand mis always incrementing ; thus # will alw: it is necessary that its condition becomes false at one point. Joop will never become false, because the condition ‘ays remain > 0. Hence it will repeat endlessly. There are tivo possible sol 7 ven (i) change the condition to some reachable limit (as per update expression) e.g; while (n ¢ 108) = dation equation of loop variable so that it makes the condition false at some atio (ij) change the ups point of time, eg.» while (n> 8)? nen-d COMPUTER SCIENCE WITH PYTHON _ ven tao code fro ip the inputs are entered in the gi se fragments, Wat wilt Be the outputs if the ips ( 9. Caner eo given onde fragment WISI ‘order are (i) ‘Jacob" (ii¥'12345° (ii i () name = "* while Teve nang = input( Af name == “end : break print ("Hello", nane) else: print ("Wasn't it fun ?*) “enter nane (‘end to exit) (rane ="* while nase I= Tend” : . | rane = input( "Enter nane (‘end to exit):” ) Sf mare «= “end” : pass - print ("Helo", nane) else: print ("Masn't st fun ?") Solution, Code (a) will print Code (b) will print i for input () for input () Hello Jacob Hello Jacob for input (i) for input (ii Hello 12545 Hello 12345 for input (i) elven for input (ii Hello END for input (i) no output will be printed for input (iv) Hello end Wasn't it fun > 10, Write Pyton code to add the odd numbers up to (and inctuating) a Solution. : N= int (input (Enter nunber’)) sum=0 fea while i c= N: sum sum +4 feiee print (sum) iver value N and print the result. U1, Consier the following Python program : Ne int(input (“Enter nz" )) ina sun=@ bite oper 4: CONDITIONAL AND ITERATIVE STATEMENTS while 1 ¢N i AFA R2=n0 sum sum ¢ 4 dadea print (sun) (a) What is the output when the input value is 5 ? () What is the output when the input value is 02 Solution. (0) — (b) 0 12, Consider the fotlowing Python program, intended to calculate factorials : number = int(input (“Enter nunber")) ni, result = cunber, 2 while True orn: result = result * n nen-2 factorial = result print ("factorial of ", number, "is", factorial) (a) What happens when the user enters a value of 5 ? (0) Howe would you fix this progeam 2 Solution. The problem is that the program will repeat infinitely. The problem lies with the condition af while loop this condition will never go false. Correct condition will be any of these : while: or whilen>@: ccond lowest nuniber from the 10 nuntbers input. 13. Write a program to find lowest and s Solution. # to Find Lowest and second lowest integer from 18 integers stall = smaller = @ for 4 in range(10): n= int(input("enter number :")) ifivea: # first number read smal elif i - 1: # second nunber read Af nce small : smaller = 9 else: smaller = small small =n else: # for every Integer read 3rd integer onwards COMPUTER SCIENCE WITH PYTHON Af nc smaller = snall = saaller smaller =n sample Run slit a ¢ soll fF the lowest number is: 6 melee | the second lowest number ig 5 print(*The lowest number is : ", smaller) a print(*The second lowest nunber is : “» small) manus “The sample run of above program (from the ten input numbers 35 © 6,13, 20, 3,15, 18, 95,4, 23) has been given above. r Sees smber between 1 and 100 and continuoyyy 14. Number Guessing Game = This program generates a random asks the user to guess the muniber, giving hints along the way. Solution. Amport randoa secretNun = random.randint (1, 160) #generate a random integer beta [2 100) puesstusString = int(input ("Guess a nunber between 1 and 180 inclusive: while guesshun I+ secrethun Af guessus < secrethun : print (“Your guess is too low.”) else: . . print ("Your guess is too high.”) . guesstun = int (input ( "Guess a nunber"between 2 and 100 inclusive:” )) print (“Congratulations! You guessed the nurber correctly.) 15, Writea Python script to print Filsnacei series’ first 20clements, Som initial elements of a Fibonacet series are: @112358.,. Solution first <0 second = 2 print (first) print (second) for a in range(2, 19) : third « first + second print (third) first, second = second, third 16. Write a Pythom script to-read an integer > 1000 and reverse the mu, Solution fun = int({nput( "Enter an integer (>1000) ‘trum = nua reverse = 6 while thum : digit = tnunx 18 ‘hum = taum / 16 Peverse = reverse * 10+ digit Print ("Reverse of", num, "is", reverse) Charter 4+ CONDITIONAL AND ITERATIVE Starewents ‘ 17. Write a Pyllion script to generate Solution, num = int(input("Enter an mid = num /2 print ("The divisors of* 1 for a in range (2, mid +1) if num % a see: divisors of a number, integer :* y) ua, "are print (a, end = * +) ty else : print ("-end-") ay] 18. Input three angles and determine if they form a triangle or not. Solution. ficheck triangle from angles anglel = angle? = angie3 = 9 anglel = float(input("enter angle 2: “)) angle2 = float(input(“enter angle 2 : ")) angle3 = float(input("Enter angle 3 : “)) if (anglel + angle2 + angle3) == 180 : print("These angles forma triangle.") else: print ("These angles do not form a triangle.") 19, Numbers in the form 2"— 2 are called Merseune Numbers, eg. 23 — Write a Pyliion script that displays first ten Mersenne numbers. Solution. program to print mersenne nunbers print(“First 10 Mersenne numbers are:") Sample Run for ain range(1, 11): First 10 Mersenne numbers are = mersnum = 2 ** a-1 137 15 31 63 127 255 511 1023 print(mersnum, end =" ") print() 20, Merscuine muntbers that are prinie numbers also, are called Mersene Prine numbers. Make modifications in previous question's Pythow seript so Uhat it also displays ‘Prime’ next to the Mersenne Prime numbers. Also, this time print 20 Mersenne numbers. Sample Run Solution. (With first 10 Mersenne numbers) # progran to print mersenne prime numbers 1 prime for ain range(1, 21): 3 Prine mersnum = 2 ** a-1 ji 7 Prime mid = int(mersnum / 2) +2 pos for b in range(2, mid): 2 Prime Af mersnum % b == 0: | 8 rime print (mersnum) {| az else: break Sat print (mersnum, “\tPrime"> fo COMPUTER SCIENCE WITH PFN ng its weight tea program to eatcutate BML of pers it igs and height in meters w sate BMI of a person efter input 21. Write a program to eateulate print the Nutritional Status as per follow" tal / ' ‘Nutritional Status. "Wo eriteria, = 3 I < 18. Overweight BB = 7 Solution, os wetght_n_kg = float(inpur("enter welaht fn KE De = helght_in_acter » float(input("enter hesght in eet ! bai = welght_in ke / ( hefght_in.meter * helght_in-s print("BHt ds :°, bal, end = i Af bmi < 18.5: print("... Underweight”) elif bal «25 : print(”... Normal") elif bol ¢ 30: { print("... Overweight") else: i print(*... Obese") | 22. Write Python script to print the following pattern + 1 33 135 1357 Solution. for a in range(3, 10, 2) = for b in range(i, a, 2) print (b, end =" *) print () 23. Write a program to find sunt of the series: S=14.x4x7 49 4x" Solution. x= float ( input ( “Enter value of x :*) ) | f= Ant (input( “Enter value of n (for x ** n) s=0 for a in range(n +1) : Stextta print ("Sum of first", n, “term: 8) Write a Python script to input two numbers and common divisor) Solution. 24. Print their lem (Leest common multiple) and ged (grees! X= Ant (input (“Enter First number: *)) y= nt (input ("Enter second nunber: ~)) h 0, Chapter 4: CONDITIONAL AND TERATIVE srareMenrs 15 Afx>y: a sealer = y else: sealler = x for 4 in range(1, smaller +1): AF((x% L = 9) and (yx 4 hef = s lens (xy) / he print("The H.C.F. of", x, “and*, y, print ("The L.C.M. of, x, "and", y, @)): “1s*, heF) “Is", len) 2. Write a Python script to calculate sum of fete series SAUD H 42643) EDD chy Solution, sun=@ ns int ( input ( “How many terns 2°) ) for ain range(2, n°2): # added 2 ton because started with 2 tem = for b in range(1, a) : term += print (Term, (a=), *:*, tern) sun += tern print ("Sun of", n, “terms 4s", sun) 26 Write a progran: to print the following using a single loop ( no nested loops) 1 n a1 un an Solution. nea for a in range(s) : print (n) nent ao+d Write a progrann to print a pattern lik ax21 432 3 4 Solution. for i in range(4): for j in range(4, 4, -2)= print(J, end =") else: print() COMPUTER SCIENCE WITH PYTHON GLOSSARY fe F sotements having sare indenatian [ve ds sf Block A oun lec stan hn lest Rede | sey The Hoefer omen mT ra Empty totement A stotement that oppeers 1 tho | tse toe Alooe a ee ends Eres oP re trrotonSetement Se! el llor oa of sons Yo bo pete OTN ! jump Statement Siolemen!thel uneonditonlly transfers proore veil teopig Stent tran soar Avo abel 910 ume Nesting Some progrom-cansne! wihin anather of some Maaseod sp. ‘loop thot contains enothor loop ise is body ‘ une Bloc é Assignments a een a Type A : Shor! Answer Questions/Conceptual Questions 1 What is the common structure of Python compound statements ? 2. What is the importance of the three programming constructs ? 5, What is empty’ statement ? What is its need ? ; 4. Which Python statement can be termed as empty 5, What is an algorithm ? 6. What isa flowchart ? How is it useful ? ' 7, What is pseudocode ? Hoty is it useful in developing logic for the solution of a problem ? 4 Wh 5. What is decision tree ? Where are these useful ? ‘ 9, Write pseudocode for checking if a number is a factor of 3215 ? 1 10, Draw flowchart for displaying first 10 odd numbers. 11. Draw decision tree for grade calculation as per ' Marks >90_| soo | 7080 | oo-70 | 50-60 | 4050 | <40 F code | wr [| a | | em | a le F 5 12. epreeaitente for comparing {wo products of two sets of numbers (a, b and c, d) and disphayingif i 13, What is entry-controlled loop ? 14, What are the four elements of a whi 15, What loop in Python ? se of if-else and else clause the difference between else cl 16, In which cases, the else clause of Python loops ? 6f a loop does not get executed ? 17, What are jump statements ? Name them. 18, How and when are named conditions useful ? 19, What are endless loops ? Why do such loops occur ? (.048z,.) 3Ufud Om Udy aq woay8 9po0 OU UT SOUND a4} ping (.2aoge 343 Jo au0U,) upad esta ((@)43s) quyad 1.8, == (@)vas 3719 (@) autad 2 ,ouaz, == (o)sas 3712 (,0492,) utd 29 == (,ouaz, )auy af {2 apoo jo souyy Susmoyfoy ays Jo ndino ayp sy yeuyy (sayaeam) aupad 2 asta (Bur HAs Suyod,) dupud 1,MOUS, = vayzeah J7Ta (aperquns Jean.) qupad 2 Auuns, = JayreaM a7 .Buyuyes, = Jayaean + 9poo ayy 1301303 { apo> SuIMOTIOJ Ut 10179 IN SEICUM (.0,) wwrad Go = Pua 24) 3UTId 2(@ =i x) aE 12> x aTT8 (. . = pua ‘a.) aupud 2 asta 1.) aupad PCKST PE xST Tex 4 9p0> Sumoyioy ay Aq paonposd andino atp st PULA *f he (.ueaas,) aurad 2 asta (.aaaem,) autud 2eTe > dues 371? i (.29F.) wd + ze > duva st wud qwawSex apoo spp pis suompuoo reyes JapUN TZ (.oesu.) aupid | 2 (€=0e) 3 (.0mL.) uted (tse) at (.340,) qpsd (pare) 3F (.ovaz,) wrad 2 (=e) a orjoy aap ALT gd + apoo ayy aus0> pure MoI G. = pua i AaeM, + sos x eo Jo saqum oxy wo soaes ye auoufe4 apay 5 rp ; Suoy|sang pasog uoyo>ddy * SINAWaLWIS aaivuaL xy NOLIGNOD # t °°? i elif tnasd print ("one") elf need: print ("two") else n= ) print (“three”) . 7. What is fotlowing code doing ? What would it P n= int (Anput( “Enter an integer” )) f€nei: print (“invalid value") else: for 4 dn range(, +1): print (1 * 4) 8, How are following two code fra following code fragments : (@) n= Ant (4nput( “Enter an integer:" )) ifn >@: for ain range(i,n +n) print (a / (n/2)) j else | print ("Now quiting”) 9. Rewrite the following code fragments using for loop = () 1100 (@) while num > 2: while (4 > @) : print (num % 10) print (4) nun = nun/16 i~3 10, Rewrite following code fragments using while loops : (2) min=@ max = nun if num ¢@: min = num max = 0 for i in range(min, max + 1): sum 4s 4 () for 4 in range(1, 16) : ifiX3=00: print (4) (© for 4 in range(4) : for J in range(s): Ufitesjorj+iang; print ("4", end=* +) else: print ("o", end= ' *y print () int for input as 3? COMPUTER SCIENCE WITH, ments diferent from one another 7 Also, Predict the ouput gg () m= int (input( “Enter an integer» ifn>e: for a in range(1, n +n): print (a / (n/2)) else: print (“Now quiting") ” (© while num >@: count += 1 sum += nun num ~= 2 if count == 10: print (sum/float(count)) break # compute sum of integers from min to max caper 4+ CONDITIONAL AND ITERATE staTEMNts 1, Preis the output of the following code fragments (@ count =e © x=20 while count < 2 poe print (“Hello*) While x > y: count += 1 Print (x, y) Xexea yeyar (0 keepgoing = True @ xmas ( forxin[t, 23,45) x= 100 while x ¢ 58: print (x) while keepgoing : print (x) print (x) xex-20 sfx 50: keepgoing « False () for x tn range(s): ©) forpinrange,10 | (H) forqinrange(t00,50,-10) print (x) print (p) print (4) ( for 2 Sn range(-500, 500, 100); © foryinrange(s0n, 100,100) print (z) print ("+") y) @) x=20 () forxin{1,23} yes for y in [4, 5, 6]: for 4 in range(x-y * 2): print (x, y) print (7X ", 4) (7) for x 1n range(3: () eno for y in range(4): for x in range(1@): oot} print (xs ys x+y) for y An range(s): 4 print (c) 12 Which of the following Python programs implement the control flow graph shown ? COMPUTER SCIENCE WITH PITHOK py while Tre * i . (@) while True = r fre ane (input ("enter an dnt: *)) f se ape tanmuecrencer an ant) fenee abt y dfnenAlt ‘ . continue ‘continue elif n= A2t elif n== AZ: break } break else: * tie ' else: print ("what") patience pring Chat") print (rever") \ else : Anyi print ("ever") i (Q_ vhtle True : ine int (input("Enter an int: “)) ifn es AL? continue elif nas A2t break print ("what") print ("ever") 13, What is the output of the following code ? for 4 in range(4) for j in range(5)? Sf ibiesforj+ian4: print ("+") end=" ') else: print ("o", end =" *) print() 14, In the nested for loop code above (Q. 13), how many times is the condition of the if clause evaluated? Type C : Programming Practice/Knowledge bosed Questions 1. Write a Python script that asks the user to enter a length in centimetres. If the user enters a negitt® Iength, the program should tell the user that the entry is invalid, Otherwise, the program should comet the length to inches and print out the result. There are 2.54 centimetres in an inch. A store charges & 120 per item if you buy less than 10 items, If you buy between 10 and 99 items, the is 8100 per item. If you buy 100 or more items, the cost is € 70 per item, Write a program that asks user how many items they are buying and prints the total cost 3, Write a program that asks the user for two numbers and print i juhin 00tol each other and Not close otherwise. Prints Clase if the numbers ore win 4, Ayyear is a leap ycar if it is divisible by 4, except that years divisil kes 3 at years divisible by 100 are not leap yeas they are also divisible by 400. Write program that asks the user for a year and printe tater leap year or not. Vu 5. Write a program to input length of three sides of a tri ‘1 z Wee a prog put length of three sides ofa triangle, Then check if these sides will form #2" Rule ista+b>erb+c>azct+a>b) 6, Write a short program to input a digit and print it in words. 7, Write a short program to check whether squai 1 fare root of a number is pri 8, Write a short program to print first odd m A prime oF nok Program to print first m odd numbers in descending order. is a 4, 4: CONDITIONAL AND ITERATIVE Starts 9 Write a short program to print the following series: 1 4 7 We... 40, wind 7-0... un. Write a short program to find average of list of m lumbers entered through keyboard, Weite a program to input 3 sides of a triangle an ue Snple and print whether itis an equilateral, sealene or isosceles 12 Write a program to take an integer a as an i input and check whether it ends with # or 8. Hit ends with 4, int “ends with 6°, otherwise print “ends with neither”. 2 input from the user, Print numbers from 11 to N. When the * when its a multiple of 7, print “Topsy”, When itis a multiple print “ends with 4°, if it ends with 8 pri 1. Write a program to take N (N > 20) as number is 2 multiple of 3, print “Tips cof both, print “TipsyTopsy” 14. Write a short program to find largest number 15, Write a program to input N numbers and then print the second largest number 46, Given a list of integers, write a program to find those which are palindromes. For example, the number 4521234 is 9 palindrome as it reads the same from left to right and from right to lett. Write a complete Python program to do the following : (i) read an integer X, (i) determine the number of digits m in X, Gi) form an integer ¥ that has the number of digits n at ten’s place and the most significant digit of X at one’s place. (i) Output Y. (For example, if X number is 2). 18. Write a Python program to print every integer between 1 and nd number that is divisible by mis even or odd. 19. Write Python programs to sum the given sequences : * of a list of numbers entered through keyboard. is equal to 2134, then ¥ should be 42 as there are 4 digits and the most significant sible by m, Also report whether the 2.5 OS 20, Write a Python program to sum the sequence 1 » (print 7 terms) (ey P43? +5? ++ 0 (nput ny a. 26-35 i)36-45(iD4O~ 55. 2. Write programs to find the sum of the following series : os q + sl 6 (Input x) 3. Write programs to print the following shapes : ® ” © o aes m a Re m7. I 28 comput race the following patterns ' rte programs using neste Lops 19 Pr @ A AB ABC | aac D f aABCOE { ApCcOEF f oe 22 44 see 8 with 6 rows and 20S per row, ice a rectangle of “S ram to write their values print out : Write a program using nested loops to produ Given three numbers A, B and C, write @ prog Sample, f Axi2, Be10, and C=15, your program should in an ascending order, Foy ‘Smallest number = 10 Next higher number = 12 Highest number = 15 Write a Python script to input temperature. Then ask them what u temperature is in, Your program should convert the temperature to the other unit F #95C +32 and C=5/9 (F 32). ‘4 nits, Celsius or Fahrenheit, the ‘The conversionsan a! ‘Ask the user to enter a temperature in Celsius. The program should print a message based on the temperature : 55 4 If the temperature is Jess than ~273.15, print that the temperature is invalid because it is beloy ee absolute zero. i If it is exactly - 273.15, print that the temperature is absolute 0. If the temperature is between -273.15 and 0, print that the temperature is below freezing. a IL it is between 0 and 100, print that the temperature is in the normal range. AF it is 100, print that the temperature is al the boiling point. Ye f a ‘4 Ifit is 0, print that the temperature is at the freezing, point. + If it is above 100, print that the temperature is above the boiling point. 51 52 53 54 55 String Manipulation ay Wi « Chapter Introduction Traversing a Suing ‘Sting Operators ‘String Slices SStting Functions and Methods INTRODUCTION You all have basic knowledge about Python strings. You know that Python strings are characters enclosed in quoles of any type — sins ¢ quotation marks, double quotation marks and triple quotation marks. You have also learnt things like ~ an empty string is a string that has 0 characters ( tis just a pair of quotation marks) and that Python strings are immutable. You have used strings in earlier chaplers to store text type of data. You know by now that strings are sequence of characters, where each character has a unique Position-id/index. The indexes of a string begin from 0 fo (length ~ 1) in forward direction and 1-2, ., ~ length in backward direction. In this chapter, you are going to learn about many more string manipulation techniques offered by Python like operators, methods etc. \ COMPUTER SCIENCE MATH Privy P 184 : ° i 2. TRAVERSING A STRING : que i 0 5.2. TRAVERSING sastingare scesible through the unique index ff 0 You know that individual haracters of Ee ring character BY a eS ‘aversing relay character, Using the ndeses 0 ig oe ca a ce aT to iterating through the ‘Ter gh unknowingly when we mlked ® long wig 7 | traversed through Stn aoe yon can write a Loop Hike * le for loops. To traverse through a string, Y Pe “ ame = “superb” pill averse er? i— ee ee |“ for ch in nang recrsargnome ste as tropes 2 : 2 end = Traversing tele: to ke | rine Cen through the elements ofa Yon ‘The above code will print : one characteratating, "| | pt soup forb- ae . « is sufficient (o create wonderful programsty | | ! ‘The information that you have learnt till now is sufficie , ; ? manipulate strings. Consider the following programs that use the Python string indexing ty display strings in multiple ways. 35 sNG O 5.1. Program to rea a string and display it in reverse order - display one character per line. inst Do not creote a reverse sing, just display in reverse order. weegint inand not | string] = input( "Enter a string :") is ei a heh “in reverse order is:") 511 Basic O} ngth » Ren(stras Since the ranget) excludes the number vob: for ainrange(-l, (-length—1),-1): mowonel ez upp me hae Eek print (stringifa] ) ihn cae of tay ering he pelos b intone eer p Sample run of above program is caer the f] enter a string : python Ae been | The python in reverse order is: 0 perfor x than h h t — vy * pers ioe jj te | 5.2 Program to read a string and display it in the form : "Ysa first character last character i Second character second last character ‘tea, . wy 3 For example, string “try” should print as : toy ror " yt " Chopier enter a string : python apozaxe 5; STRING MANIPULATION a ueaszo stringl = input( “Enter a string :*) length = len(string1) i=@ for ain range(-1, (-length-1), -1) : [When youve ances ot ji : ids length of st print (stringi[1], "\t", stringi[a]) BSE forware Paes on es dasa Sdettered string 5, S[-1] will ‘give $[-1 + 5] fe, 5 [A] letter ; Sample run of above program is : for S{-5], twill give you SI-5+SlLe,,5 (0) | A | STRING OPERATORS In this section, you'll be learning to work with various operators that can be used to manipulate strings in multiple ways. We'll be talking about basic operators +and *, membership operators in and not in and comparison operators (all relational operators) for strings. 5.3.1, Basic Operators The two basic operators of strings are : + and *, You have used these operators as arithmetic operators before for addition and multiplication respectively. Bul when used with strings, + operator performs concatenation rather than addition and * operator performs replication rather than multiplication. Let us see, how. Also, before we proceed, recall that strings are immutable i¢,, un-modifiable. Thus every time you perform something on a string that changes it, Python will internally create a new string rather than modifying the old string in place. Sing Concatenation Operator + ‘The + operator creates a new string by joininy 1g the two operand strings, eg., “tea"+ “pot” Will result into Taw inp stings ine (concatenated to form anos sting ‘teapot’ i Consider some more examples ? Expression will result Into vet ut | nar 470" ao "127 + abe "123abe COMPUTER SCIENCE yay af ly. Python creates a new strin, frst string. operand followed ree t st the racters of first a wed (sce below) ne os i ‘we elt] - Lt elt] New sing an Pn Soop « i ings are immutable ; new strings can be F Original strings are not modified a5 strings a ele cons | existing strings cannot be modified. i re ct + operator is that this operator \ “Another important thing that you need to know about t h orem wath mumters and tings separately for addition and concatenation respectively, but inte expression, you cannot combine munbers and strings as operands with a + operator, For example, coulont 24355 # addition - VALID anol Perrey # concatenation - VALID with: f “a But the expression ae \ ‘B43 Fore i} is invalid. It will produce an error like : 2 vores Pome = 2 Traceback (nost recent call last): The + operator has to hare File“epyshel1#2>", Line 2, in cmodules Seema nes ae 7s celther of number Lie addition) of of strlng tyes let TypeError: cannot cencatenate'str’ and ‘int’ objects multiplication. 1 caaot sat ‘with one operand as suing ‘Thus we can summarize fone as a number. + operator as follows : Table s.1 Working of Python + operator [ Operands’ data type Operation performed by + Example Bumbers addition = 949-18 concatenation, "9" + "9" = "99" The * operator malfplicion and ream eit tmberS (ie, when both operands are numbers) it pero Tousea® operator sae the product of the two number operands. BUMbES * String OF gig ES YOU Need two, . ie String * number types of operands ~ a string and @ number, aeat ab awe §: SENG MANPUATION - 187 Where string openmnd tells the 5 an tring t i . sees itis to be repeated: Python a to be replicated and number operand tells the number of vil creat " sing operand. ate anew string that is a number of repetitions of the Fer example, 3 "pet" [NOTE | [fot repeston operator *, jon soba erat wring epi sia Python creates anew sting that ‘gotpotgor ay femn whine nan ni anumbe tent Consider some mare examples : will resut into “abcabe” vor Another important thing that you nced to know about * operator is that this operator can work with numbers as both operands for multiplication and with a string and a number for replication respectively, but in the same expression, you cannot have striigs as both the operands with a* oper For exemple, 2306 # eultiplication - VALID rea ea replication ~ VALID bet he exprsion NOTE a rer |The operator hasta ether have both operands of the number id. It ¢ an error like : types {for muhtpiation) or one is invalid. It will produce an ra ecient nor Alor replication). cannot work with both operands of string Traceback (most recent call last): 8 File“cpyshellea>", Line 1, in crodule> me sys An ‘ste Typetrror: can’t cultiply sequence by non-Int of type’s — Thus we can summarize + operator as follows + Tete s2 Working of Python * operator 7] same | [opera datatype | Operation performed by*|_—_—_B punben | mmultiplieation a Sas number seplication aor ener (uumber, string | replication COMPUTER SCIENCE WITH PrTHOH sequence types). These are in \ 5.3.2. Membership Operators briefly. Let Us lear about hes ings (in fact for all H ‘There are two membership operators forstrings re pei i not in. We have talked about them in Pre operators in context of strings. Recall that : sats in the given string ; False otherw i in Retumns True if a character ota substring e¥st5 the . ; are rele ‘se in the given string; False othery rat in Returns True ifa character or a substring does Not exist in the BN < i th operands used wij | Both membership operators (when used with strings), require that both ope with them are of string type, fe in not in C8 "12" in "xy2” "12" not in "xyz" i Now, let’s have a look at some examples : | va" in “heya” will give True ‘ "Jap" in "heya" will give False "Jap" in "japan" will give True “Jap” in "Japan" will give False because j letter’s cases are different; hence *jap” is not contained in “Japan” "Jap" not in “Japan” will give ‘Truc becouse string “jap” is not contained in string “Japan” "123" not in "hello" will give True beeause string “123” is not contained in string “hello” "223" not in "12345" will give False because "123" is contained in string “12345” The in and not in operators can also work with string variables. Consider this : >>> sub="help" | >>> string = "helping hand | >>> Sub2 = HELP >>> sub in string True >>> sub2 in string False >>> sub not in string False >>> Sub2 not dn string True Chopter 5 : STRING MANIPULATION 5.3.3 Comparison Operators Python's standard comparison to strings also. The com character-by-character com ‘Operators jc, all relational operators (<, <=, >, >=, =5 !:) apply arisons using these operators are based on the standard Parison mules for Unicode (i.e, dictionary order) Thus, you can make out that will give True "abc" == "abe" will give True sat I= “aber Will gi True will give True will give False (Ietters’ case is different) True (letters’ case is different) Equality and non-equality in strings are easier to determine because it goes for exact character matching for individual letters including the case (upper-case ot lower-case) of the letter, But for other comparisons like les than (<) or greater than (3), you should know the following piece of useful information, will give As internally Python compares using Unicode values (called ordinal value), let us know about Some most common characters and their ordinal values. For most common characters, the ASCII values and Unicode values are the same. ‘The most common characters and their ordinal values are : Table 8.3 Common Chorocters and their Ordinal Values Characters Ordinal Values O's 48 to 57 “AtoZ! 6510.90 “a to'z! 97 0 122 Thus upper-case letters are considered smaller than the lower-case letters. For instance, we will give False because the Unicode value of lower-case letters is higher than upper case letters; hence ‘ais greater than’, not lesser, True for obvious reasons. BC > AB will give % ‘a8’ —will give False because letters of ‘abe’ have higher ASCII ses Bie ues compared to “ABCD “aber >‘abco" will give True because strings ‘abed’ and ‘abeD' are same till first three letters but the last letter of ‘abeD’ has Tower ASCII value than last letier of string ‘abcd’. hwo strins Nu ational operators usin; Thus, you can that Python compares two strings through rel per 1B chancery cheeter comparison of their Unicode values. COMPUTER SCIENCE WITH PrTvigy ot a 90! ‘er ; i single Chorocte' “ Determining Ordinal/Unicode Volve ae i" «es a single character and Tetums the python offers a builtin fancier ord) I pe folOWiN format : one y ponding ordinal Unicode valu? tis ora(), ## the ordinal value is given in integer Havea look et some examples (compare with the Table 5:3 given above) : j >>> chr (65) 1 x >>> ehr(97) ig t a 5.4 STRING SLICES : ‘As an English term, you know the meaning of word ‘slice’ i ie mies ice’, which means — ‘a part of’. Inthe same way, in Python, the term’string slice’ refers to a part of the string, where strings arestw " using a range of indices. That is, for a string say name, if we give name| 1: and mare integers and legal indices P Python at etenaat of the string by retuming the characters falling bet ween indices n and m ~ starting at +1, 042 .- till m1. Let us understand this with the help of examples. Say we | wea string namely word storing a string ‘amazing’ zee Part of a string contalrrg 57 contiguous characters fom * string. 0 ? z 1 2 3 4 é word a m = i 7 I 7 4°65 4 3 E Then, word[ 8:7] will give [amazingly ; I | (the letters startin, ‘l oe (he letters starting from index 0 going up till 1 ie.,6 from indices 0 to 6; both inclusive) vend 0:37 wi give (letters from index 0 to 3-1 ise, 0.40 2) Yay Ot at 21.8 This works even for n negative or out of bounds. 5: STRING MANIPULATION — 1 rdf 25] will give FER S 1 (letters from index 2 to 4 (ie, § — ») k mc fom indices ~7, 65,4 ‘excluding wore[-7 = “5: -1] will give word{-5 2] will give ‘azter (ete omnis 5,-4.9, 2extadng From above examples, one thing must be clear to you : Ina string slice, the charact j ; @; ihefenile ‘er at last index (the one following colon (: ) is not included in Inastring slice, you give the slicin skip either of the begin-index of Ia begin-inder, it will consider 0 (the of the string. 1B Fange in the form ft st, Python will consider first index) and for mi *shrindex> : ]. If, however, you + Ue limits of the string i. for missing issing last value, it will consider length. Consider following examples to understand this : word[ :7] will give "amazing (missing index before colon is taken as 0 (zero) ) word :5] will give ‘anazi* (-doy word(3:] will give “zing (missing index after color length of the string) ) word[s:] will give ‘ng (-do) The string slice refers to a part of the string s{startend] that is the elements beginning at start and extending up to but not including end. Following figure (Fig. 5.1) shows some string slices : jeltostingté hetlastringtasso] , see PALL eT] oem (ele TTT] vee [TT fox fo 123 4 5 6 7 8 9 10) is ar im a holloString[ :5) Peloseingl2:-2) soon PTS ena) oer Pale eee bees [0 456789 0 rd fO1 2345676910 wo i2s | ipazo apse fist lost lost fins Figure 5.1 String Sticing in Python. tr " “resting Inference 4 ill find that Usin, ing slicing technique, you wil . ig the same string slicing Il give you oxiginal sing s © for any index n, wiin),5 4. How are strings Internally stored 7 2. For a string # storing “Goldy, what vould [0] and sf-1] return ? 3, The lst character of a string s Is at Index len(s) = 1. Tue / False ? “4. Tor strings, + means (1) ; * means (2). Suggest words for positions (1) and (2). 5. Given that ste "span” s2erntl” What Is the output produced by following expressions ? (o) * The Knights who say, * + 52 () at ere 2e sz © salt] 6. What ace membecthip operators? What dda they basically do ? (On what principles, the strings are compared in Python ? 8. What will be the result of following ‘expressions ? (a) "Wow Python” (1) (0) “Strings are fun.” (5) (c) len(“awesome™) (A) "Mystery" [:4] {e) “apple” > “pineapple” “pineapple” < “Peach* (g) “cad” in “abracadabra® (8) “apple” tn “Pineapple” ()) "pine" in “Pineapple” 9. What do you understand by string slices 2 10. Considering the same strings s1 and 52 ef question 5 above, evaluate the following expressions : (@) safazay @) s2[2] +s2f:2) (@ st+s2f-2] s1[:3] + s1[3:] s2[-1] + 82[-1:) COMPUTER SCIENCE WMH POY, ve this with an omely roved storing “amnmzis yo word 32)» word (23) ‘zing "389" / Jy word 13] + word 3#T ‘amazing / poo wora(:-7], word (71 ++ tanazing’ yoo word :-7] + H0rd( 78) ‘amazing i index (say m) in string sf You can give a third (optional) index in sting hg woe eid that every nth clement will be taken as part g cimeegy for word «‘amazing’, lookat following example, >>> word [1:6:2] 1 will take every 2d choraeter sartng fm index = TH den «6 ‘man’ >>> word [~7 Iwill take every Ind character ne ong fram index = =P der €.5 po word ovry 2nd churscter takes acne ‘pioa’ »oword (: :-2] ‘pint very character tae bachwent, Another interesting inference is : © Index out of bounds causes error with strings but slicing a string outside the bounds does not causeerrot, 5 = "Hello! _____ vty cause eror becuse $s Tessa Python’ print (s(5]) Fnewsout of towed, for sing el? But if you give s* "Hello" print (s[4:8]) print (s[5 : 10]) ; ~~ otk limits are outside the boos the above will not give any error and print output ° a ee ting ie, letter 0 followed by empty string in next line. Te reason behind this is that when you use an index, you ® accessing a constituent character of the string, thus Track must be valid and out of bounds index eauses ero"™ sha JS ne character to return from the given inde. Bt slicing always returns a subsequence and empty sequt® isavalid sequence. Thus when you slice a string outside _——— One lint fs outside the bows lengua of Hello is $a ha ved fndexes are 0-4) example. Consider the sameaing [aid estri inte follow demeaning | era string va Letus now h Fepeapttalize bounds, it still can return empty subsequence and yibon gives no error and retums empty subsequen® Truly amazing ;) Isn't it 2, 5 STRING MANIPULATION, ye on Program that pri Ayss Pros POPS the (lo wi0g etary , ve ‘lthout using any nested Joop wr or thay hang string = Sample rin of the program is as shown below : pattern=ss 1, forain range(s) ; mpty String \ ” Pattern ye string yom Print (Batten) | tne tee 55 STRING FUNCTIONS aN METHODS Python also offers Many builtin already worked with one sud retentions and methods for ste about many other built-in power set HAG) in ear werful Every string object that yo. do anything specific for pulation methods th; cnet In the following table We are the meaning is intact j, or a string variable th Let us now have of String class (you need not ipdiscusgat see {now built-in). The siting mani- Stting as pet following syntax: pa nerting . as string only (no angle brackets) but Told eo replace string with legal string (i, eithe i at holds Sting vases Ig a legal string (i either a string literal, look at some useful bu: Table 5.4 Python’s Built-in String Manipulation me |steing.capitalize() | | Example | >>> "tev .capitalize() True | >>>" $ love ny India’ capitalize) h_ | T love my India String.find(sub[, start[, end]}) | Returns the lowest index in the string where the substring sub is found within the slice range of start and end, Retums -1 if sub is not found, le = string ='it goes as - ringa ringa roses’ >>> sub = ‘ringal | >>> string. find(sub) B | >>> string-find(sub, 15, 22) \ | a | >>> string. find(sub, 15, 25) | 19 COMPUTER SCIENCE WITH Pry, * 194 are alphanumeri in the string iphanumeric (ap 0 Returns Tre if t3e eeriger one reactor False otherwise, Pg) string.dsalnum Haris at rrurnbers) 3 Example >oo string = ae poo string? «Pel pop string} p>» steingd = tring-isalnum() >? 8 True poo string2-dsalnum() true >>> string3-iselnun() True >>> stringé.dsalnum() False >» string-isalpha() string.isdigit() Returns True if all characters in the string are alphabetic and there is at lxs| one character, False otherwise. Example (considering the same string values as used in example of previous functin- isalnum) >>> string. sal pha() False >>> string2.isalpha() True >>> string3.4salpha() False >>> strings. isalpha(’) False Retums True if all the ch fone character, otherwise it retums False. Example (considering i i srserns the same string values as used in example of previ >>> string. isdigit False ° >>> string2.isdigit False ot) >>> strings. isd, True Sdigit() >>> stringa. 4. False sdigit() ‘aracters in the string are digits, There must bet est os fot" | string = STRING MANIPULATION contr 5 = STR 195 slower() Returns True if all cased {haracters in the string are lowercase. There must be St least one cased character, It relums Fale ele Example >>> string = ‘hell >>> string2 = THERE: >>> strings = ‘Goldy >>? string.tslover(’) True >>> string2.dslower() False >>> string3.islover() False string.1sspace() | Retums True if there are only whitespace characters in the string. There must bbe at least one character. It retums False otherwise, | | Exampte | >>> string = >>> string? 2> string. isspace() # stores three spaces # an empty string | >>> string2?.isspace() | False | tring. . fests whether all cased characters in the string are uppercase and requires otherwise. | example >>> string = "HELLO" >>> strdng2 ="There™ >>> string3 = “goldy” >>> stedngd = "U123" character in uppercase 99> strings = "123f" # character in lowerease >>> steing-isupper() True >>> string? Asupper() False >>> string3.isupper() False >>> stedng4.isupper() True 39> strings Asupper() Folse 196 | steing-2ower() string-upper() COMPUTER SCIENCE WITH PYTHON _ onverted to 1owercase string 3 id in example of 2? steing-lower() ‘hello >>> ‘string2-1ower() >> string? -Lower() po strings Jower() ciring converted (0 UPPEPCASE res a8 used in example of previcus Returns a copy of the Example (considering the same string Wal funetion - isupper) oo» string-upper() WELL por string2.upper() “THERE >»9 string3.upper() "sour" >>> stringd.upper() uns ooo stringS.upper() 3 | string-Istrip([etiars]) string-rstrip({chars]) LEER TMERO atthe ond af iste Relurns a copy of the string with leading characters removed. | IC used without an argument, it removes the leading whitespaces. ‘One can use the optional chars argument to specify a set of characters to be | removed. ‘The chars argument is not a prefix; rather, all combinations of its values Gl Possible substrings from the given string argument chars) are stripped when they lead the string : Example 4 The example for Istrip( ) requires a detailed discussion, hence we 2 Biving example of Istrip( ) at the end of this table. Returns 2 copy ofthe sirhig with trailing characters removed. M sed without any argument, it removes the leading whitespaces. rs argument isa string specifying the set of characters to be remove’: “The chars argument is ni : 3 sinpped, “BUEN not a sufi; rather, all combinations ofits valves =? Example * The example for rstrip( ) requires oa siving example of rates a detailed discussion, hence the endl of this table. posse 5: STRING MANIPULATION Exomple fer Istip( ) function 229 string "hedge So prenenapl he mand >>> string.Astrip(y = tetera eng ‘hello’ 2>> String? «There moe! sigs ond fend “There® >>> Sting tegen ae Ry FM tle mm “There moved oe rae 2>> string2.Istrip( they The Te he Teo Te eon ce rh Ne al >>> string2.Astrip(he) Es aencialabaias! ‘There! meee >>> string2.2steip( ‘Tet “here? >9> string2.Isteip(Tett ‘re oT ke ands mena estringzastripcnery “Sarah J ies ead QB Ti fond nd On the same fines, you'll be able to justify that >>> “saregamapadhanisa”, Istrip( “tears” ) “genapadhanisa’ >>> "saregamapadhanisa”.Istrip( “races* ) ‘ganapadhanisa’ sf Example for rstrip| ) function err 1. What is the role of these functions ? ‘The rstrip( ) works on identical principle the only difference is that it matches from right direction, Consider following examples. We know (9 tsalphag ) (i) isstnur¢ ) understand if you have carefully read the (ii) isdigit( ) Cu) isspace( ) examples, 2 Mane the case related string mani Pulation functions. >>> string % How is istowes( ) function diferent ‘hello! from lower( ) function ? >>> string.rstrip() ba What is the utility of find{ ) function ? hello 5 How is capitalize) function diferent bo string? 182 ¥ppe) function ? ‘there Kow da Utrip( ) and rstrip( ) functions wok ? pop string2.rstrip(ere’) as that of Istript), + You'll be able to reasons for Istrip( ) i ‘care’ >o> string2- pstrip(‘care. ') i wry stringz.nstripCee") "There > ecorit} > sareganapadnanisa” estes neear’ ‘sareganapadhant” yoo “sareganapadnant™ ‘sareganapadnani” _estrip( “races” ) caguatrings is en() function which g1VeS you the wn that you have used with string sistent) tna you se 38 leg of characters containes (One more funt of the string as the count len(estring?) For example, pop string s‘hello) >>> Ten( string) 5 Consider following program that applies some of the string manipulation functions that you have learnt so far. 5.4 Program that reads a Hine and prints its statistics like: m Number of uppercase letters: Number of lowercase letters: Number of atphabets : Number of digit Line = input( "Enter a Line Lowercount = uppercount = 0 digitcount = alphacount = 0 fora in lip Sample run of the program is : ifa,islower() : leven Enter a Vine : Hello 123, ziPPy zip elif a.isupper() ¢ Number of uppercase letters + 7 uppercount 41 Number of lowercase letters : UL sarin : Number of alphabets ; 18 eitcount Nunber of digits : 3 if a.isalpha() ° alphacount +=1 print (*Nunber of uppercas " ei print (*Nunber of lowercase letters print (*Nusber of alphabets ;", alph print ("Nunber of digit leiteoon " , Uppercount) » lowercount) ‘ount) + digitcounty il Joy = 5: STRING MANIPULATION ow 5 Program tha reads a in ana sy 2 $5 Promon tt read jie onda subs “A tod en ny tender ecm ap leq" Hine = input “enter tine ;= > sub = input( "Enter Substring ;« ) Jength= Jen(1ine) Jensub = Len(suby start = count <9 end» Length while True ; Pos = Hine. Find(sub, start, end) Af pos I= -1 count +23 start =pos + lensub else: break if start > length : break Print ("No. of occurrences oF", sub, + count) Sample runs of above program is Enter substring : jingle So. of occurrences of jingle : 3 RESTART ewe. |, Enter Tine : jingle belis jingle bells || Enter substring : bells No. of occurrences of belis : 2 | enter Vine : jingle bells Jingle bells jingle aN the way ingle all the way jp STRING MANIPULATION Progress In Python 5.1 a ssion works on the objective of practicing String manipulation operators D Tis Progress in Python’ and functions, Please check the practical component-book ~ Propres in Computer i Ih Python and fill it there in PriP 5.1 under Chapter ins Nt procticelly doing it on the computer. ppottece Her Let eeee eee Solved Problems a 2. ere COMPUTER SCIENCE VITA Pry, " Us REVISE pa Python strings are stored In memory by storing Individual characters In contiguous memory fotos, strings re stored In me : \ ‘The memory locations of string characters are given indexes OF er ieee tig The index (also called subscript sometimes) is the numbered posit ‘elpted and, 2 tp | In Python, indices begin 0 onwards in the forward direction up 10 “ern acloword direction. This is called wo-way indexing. For strings, + means concatenation, * means replication, - | ‘The in ond not in are membership operators that test for @ substring’s presence In ie aria. ‘Comparison in Python strings takes place in ditionary order by applying charocter-by-character comparigg ry, for ASCII or Unicode. The ord ) function returns the ASCH volue of given character. ; ; The string slice refers to.a port of the string s{start:enil] is the efement beginning at start ond extending Up ob Including end. i The string slice with syntex sfstart: end nis the element beglaning ot start and extending up 10 but ot ey, end, tching every nth character. thon also provides some builtin string raaipulation methods like: capitalize), find), Isalnumt ), isp Isdiglt(),islower{ J, isuppert ), lower( J, upper(),Istrip( ), rstrip( ) ete. ee | is it useful ? e ofa string, say s, can be obtained using s [n : m] where 1 and max m=1 eg What isa string slice ? How Solution. A sub-part or a sh legets. Python returns all the characters at indices 1.11, 17 "Well done’ [1:4] will give ‘e11* Figure out the problem with following coe fragment, Correct the cote an then print the output. 1, sl =" must! 2. s2e'try" 3. ne a9 4. 203 S. print (51+ s2) 6. print (s2* n2) 7. print (si +01) 8. print (s2* s1) Solution. The problem is with lines 7 and 8. © Line 7- print s1 + n1 will cause error because 51 bei i ted ing a st f a number n1, ‘6 4 String cannot be concaten: teem be solved ether by changing the operator or operand eg. all the fal" (@) print (52 * ni) (@) print (52 + ste(na)) (¢) print (si+s2) co Ghapier 5 = STRING MANIPULATION © Line 8 print (52 » $1) will ca The comected statement will bes" MSEC Two stings cannot be used fr replication. Print (524 51) ‘try must 3. Consider the following code : Strang = input("Enten a string ; count = 3 while True : Af string[o] w= 'x : string = string{2 :] elif string{-1] =='8 : string = string [+ 2] else: count +01 break print (string) print (count) What wit! be the output produced, ifthe input i (i) aabbee Gi) anced Solution. (a) bbe) ce ee 4 4 4 Consider the following code : Inp = input( “Please enter a string : While len(Inp) Af Inp[-1] == 2: feondition 1 Inp = Inp (0: 3] +'¢ elif a‘ in Inp ‘condition 2 Inp = Inpf@] + ‘bb’ elif not int (Inp[0]) : feondition 3 Inp ="1' + Inp[1 :] +'z else: Inp = Inp +'* print (Inp) What will be the output produced if the input is () Ibzz, (i)' 0" (ii Solution, COMPUTER SCIENCE WITH PrTHoy, 202 x 1ex 0 and condition 3 will (ii) endless loop because 'f will always remain at index 0 and ¢: be pay endlessly. i) Lx yer em ° Raises an error as Inpl0} cannot be converted t0 in! 5 st mi rus amd then capitalizes the first letter of eck ig with multiple wor 5, Write a progrant tat takes a string t forms a mee string out of Solution. ‘string = input( “Enter a stein ength = Len(string) are tend = length string? aenpty string while 2 < Length : SF ass: string? += string{@]-vprer() aan elif (stedng[a] == 1" and string(aea] != string? += string{3) string2 += stringfa+1] -upper() ate2 else: string? += string[a) ater print ("Original String :*, string) print ("Capitalized words String", string2) 6. Write a program that reads a string and ehecks twhether it is a palindrome string or not. Solution. string = input( “Enter a string :" ) length = len(string) nid = length/2 rov=-2 for a in range(nid) = 4f string{a] == string{rev] : else: print (string, "is not a palindrome") break else: print (string, "is a palindrome") 7, Write a program that reads ¢ string and di Wie 'g and displays the longest substring of the given string ling jst ™ Solution. string = Snput( "Enter a string : Jength = len(string) ae Mg | or 8 NS MerUANION " rarlength = 0 203° nant = ws tensed = 0 for a tn range(leogtn): $f stringla) tn setoy 10 Lensub > ni ansub » sub | rarlength » Lensub subs" ensub « 6 else sub 42 atetngtay Tensub « Len(suby aed Print ("Haxdoum length consonant su print ("with™ , maxlength rane ts oy mans characters") § Writea prog passion becomes rare that toads a strin ard thes Solution string = inpur( “Enter a string :* ) Length = len(string) print (“Original string :*, string) string? «** F expty string for a in range(a, length, 2) : string? +« string(a] Af a < (length-3) + string? += string[a + 1).upper() Print (“Alternatively capitalized string :* , string2) Solution rail « input( “Enter your enail id :* domain = ‘Gedupillar.con* edo « en( domain) # Ledo — length of domain Jena = len(onail) # Lena ~ Length of exail sub = erat [lena-ledo :] $f sub «« donain : Af Ledo != lena : print (Ie 1s valid emai} 4d") else: . print (“This 4s invalid eeafl 1d - contains Just the danain name.*) else: print (*This emall-id 4s either not valid or belongs to sone other domain “apd 2283nqap Lome noge sx[0} ose sajdeyp sRAL YOYTAa UF suoRdsoxD pue siOLID sniey Sursiingop yo "9p! NOK soar 1 “ours ayy ynoge spe) soidey> spy, “suoNdadx® Pure S101%9 yosed noge soy ROK j1 wesdoud nod Bngop Ajaanaayjo ues nox SuS8nqap payes s} ssav0ad sey, “2945 zone $1 2P09 at) tnun apo amp apidwoaos pus wioyy Aygoo4 (6)z0339 ay PUY sioWUEAZaL, “aspyd qwoudojasap Fuznp ur daais 0) punog are sion Sunpawos 207 wresoud ayum nok au, “auttooino pansap Y-10x19 Ue St HONDLYSHes JASN Jo UOLAILD JUO PUY “UOHDL|sHes Zosy 95 Aqpanpayja pauSisap aq pinoys oavanyos auf ‘SMeLL “ySnouta parysios $1228 211 ‘donnjos pozuoynduios ayy Aq paaias axe sash jo sjuowarmnbas ayy [fe 9 sta{gard 7PSN ©} suonA|os Aainduios apraosd 01 padojsaap are swOS45 wayeULOpUT Pasuaindwo> aad se Suppiom apoa any JOaaypalqo sy joa oj sv. NOLLINGOULN 1201 s068nqag Bus 9 can be creates the individual el you pass in another list, the 1d of sequence morn object including strings, tuples, and lists. Python list from the individual clr z lst funtion makesacopys mmf Ped neuen. Consider following, examples >99 d= list(‘hel lot) vod * th, 'e, Ui 1 i crear anther soguence ating “het (i penraed ind elements fom the India ter ofthe wing pote (W,'e,'r,'t,'y) poo Ide Mst(t) . SS rit mi trp nial ees for he Re) feds conn eos pe rota fram another sequence You can use this method of creating lists of single characters or single digits via keyboard input. Consider the code below : 11 st(input( ‘Enter List elenents:")) enter List elements: 234567 ood — (2,3, 4, °5,,'6, 71 Notice, this way the data type of all characters entered is string even though we entered digits. Tocnter a list of integers through keyboard, you can use the method given below. Most commonly used method to input lists is evalfinput()) as shown below : I: col) wis t ety pe by looking at st « eval (input( "Enter list to be added:" )) 4————~ ‘he gin eprestion (Rud on eat pape) print (“List you entered :*, 11st) See it erat te lett of it ing foc of the character input When you execute it, it will work somewhat like : Enter List to be added: (67, 78, 46 23] Ust you entered : [67, 78,46, 23) Pease note, sometimes (not always) evall) does not work in Python Shell At that time, you can » sometim c Tun it through a script or program too. 7.2.2 Accessing Lists suo an emresson sens iy \ | ate and return the re to evalu “The eval, )fancia of Py can Be w#e9 For example eval('5+8") will give you result 36 33 Similarly, following code fragment y+ eval("3*10") print(y) will print value as 30 Since eval() can ia pres wu can use it with inpul( ) too M rerpet an expression given as string, You ca" UES with inp ir am i an ex vari = eval (input("Enter Value:*)) print(vart, type(vart)) Executing this code will result as: enter value: 15 +3 48 1543" as 16 but also stored the result as int value. Thus . the eval() has not only interpreted the string vari = eval (input ("Enter Value:")) vara = eval (input ("Enter Value: “)) print (vara, type(vard)) print(vart, type(vard)) Enter value: 89.9 Enter Value: 75 89,9 75 You can use eval( )to enter alist or tuple also. Use [ | to enter lists” and () to enter tuple values vari = eval(input (“Enter Value: ")) var = eval (input("enter Value: *))| print(vard, type(vari)) print (vari, type(var1)) Enter Value: (2, 4, 6, 8) Enter value: [1, 2, 3] @, 4, 6, 8) O, 2, 3] ‘However, use of eval( ) may lead to unforeseen Problems, and thus, use of eval( ) is always ascouend ] Lats TUleble (editable) sequences having a progression of elements, There must bea!" ces is individual elements and Fo ee But before we start acessing indivi a ity Of Lists with tri a to} Pantie ‘ strings that esr} re cnigtidual elements are accessed in lists ~ the way you one sum aiets Following hoot 7: UST MANIPULATION, Similarity with Strings 231 & agen stings. tn the some manner fe. REC figure 31 of chapter 3 Wee tae ence 9.4.23. and backward indexing og oh TEM ae als indeed te. forwert none Maem 05-12. Bo Sec eng ee orwanindonngas shen ey elas at slesdol ue Saracer as nag Esch tne nrc dors fare (6) Mow ists ae internally ciganized a Thus, you can access thelist elements just like ess astring’sel ist wi you access astring’s elements cg, List{i will give you the element at ith index of heist; Lala. will give you samen blows nese b~1 and so on. . Put in another words, Lists are similar to strings in following ways : © Length Function len(L) returns the number of items (count) in the list L © Indexing and LL] returns the item at index / (the first tem has index 0), and L[i:j ] returns a new list, containing the objects at indexes between i and j (excluding index j). © Membership operators Both ‘in’ and ‘not in’ operators work on Liss just like they work for other sequences. Thatis, in tells if an clement is present in the list or not, and not in does the opposite. © Concatenation and replication operators +and * The + operator adds anc list tothe end of another. The * operator repeats alist, We shall be talking about these two operations in a later section 7.3 ~ List Operations. wn COMPUTER SCIENCE WITH PITHON - fo p coessed — ind nis list are a ‘Accessing Individual Eleme’ ements of 8 : e ot “As mentone the individal em apes Wille 222536 elemen,y FO h their indexes. Consider you pass In 3 negative Le throug} w) Python adds the length oye? | soo vowels» (3 oe Igtto the Index to get element $0 39 vowels [2] forward Inder. Tha is fet 3 Gelemert Ht L, Us) way i Internally computed as: 2 vote TU a soem, gre 2 vasa 2 aw 1 >>> vowels[-5] te ne v = 1 or length, ~ length +1, 100F ; ve tne legal indices (0 t0 lenght i one Uke tring you give index cur ee Python wil raise Index Error (sce below) ites uptll -1) while accessing individ val elem wy >>> vowels =['a, "et, ‘0, U] and aes {5 sno ea inde for vowels tis. thus eariot So voweli[e) ie eat te acces atid element ) Traceback (rost recent cal Last): | File “", Line 4, in crodule> | vowels[5] | Cor | Indextrror: List index out of range it mt Difference from Strings : Although lists are similar to strings in many ways, yel there is an important difference in 1 mutability of the two, Strings are not mutable, while lists are. You cannot change individual elements ofa string in place, but List allow you to do so. Thal is, following statement i fully =m valid for Lists (though not for strings) : Lf] =celenent> | For example, consider the same vowels list er reated « ; Now if you want tochange same of these vowels. above, that stores all vowels in lower case. . You May write something as shown below: Sa > voels[o] vowels Notice, it change the eerent in at (A, 'e, tv] feces 0 A) no mew [ont | >>> vowels[-4] a" MUTABLE, i Hists are Usts are similar to strings At: >>> vowels many ways like indexing, sliché At - i CAE, 0, uy and accessing individuatelemens | |g t , but they are different inte | | gg I Traversing a List Sense that uists are metobe | | Recall thas while strings are not. ¢ at traversal of a = cy | traversing alist also means Went Mea access Ma t Why sometimes we calf nett S2m€ and same je eqn PFOCessing cach element o Y } calla traversal as | is the tool for it, ip looping overa sequence,” the Python loops. That 5 P over the itemsin alist, as per following syntax: for in cLists; = . process each tes here For ample, fllowing loop shows each item of L=(P,Y,'t, foraint: print (a) list L in separate lines : The above loop will produce result as : How it works The loop variable a in above f loop-variable 3 will be iteration, » will get ele loop will be as assigned “Pin first ite ment ‘y" and ‘y’ will be Ifyou only need to use th and len() as per followin signed the List elements, one at a time. So, “ation and hence ‘P’ will be printed ; in second Printed; and so on. we indexes of elements to access 1g syntax them, you can use functions range( ) for index in range(en(t)): process List[index) here consider program 7.1 that traverses through a lis using above format and prints each item of a list L in separate lines along with its index Pp FA Program 1 print elements of a hist [4 both inde tive und negative. an LaLa, We, ty) length = len(L) fora inrange(length) : print("at indexes*, "©. ¥°J in seporate lines along with element's “and”, (a - length), “elenen! Ua} Sample run of above program is : | At indexes 0 and -6 element : q At indexes 1 and -5 elenent : w At indexes 2 and -4 elenent : € | At indexes 3 and -3 element : | At indexes 4 and -2 elenent : t | At indexes 5 and -1 element : y Comparing Lists You can compare two lists using standard comparison operators of Python, i.e.,<, >, Python intemally compares individual elements of lists (and tuples) in lexicographical order. This means that to compare equal, each corresponding clement must compare equal and the {wo sequences must be of the same type ie, having comparable types of values. fs etc. Consider following examples: devia, L2= EL, 2, 3p (2s 2 3] pode, [2,31] >>> LD am L2 True poo Lies La os canding elements of two Hists must by est For comparison operators >< >=» <1 the eoeespe comparable types , otherwise Python will gi ove two lists : For fist comparison, Psion didnot give any eroras fot at hae vals of Sere fp Consider the following considering the ab poo Lela xaeare faise For sco compari, 2 he aes of >>> Ld ”, line 1, in »>d= [2.0, 3.9] ven [2, 3, 4] D> aeeb True . >» False Fee m0 tts be ‘alues(ecal int anf There is also a emp) functio, covering it here. 73. UST OPERATIONS The most common operations and slicing lists. In this section, we are going to talk about the same. 7.3.1 Joining Lists Joining two lists is very easy operator +, when used with tw >>> Istl=[1, 3, 5] >>> Ist2=[6, 7, 8] >>> [stl + Ist2 (1, 3, 5, 6, 7, a} As you can see that the sesu clements of second list Ist2. You can also join two or more lists to form a new lst, eg, o> [sth = (40, 12, 14] 999 Ist2 = (20, 22, 24] >>> 1st3 = [30, 32, 34] >>> Ist = 1st1 + 1st2 + 1st3 >>> Ist (ie, 12, 14, 20, 22, 24, 30, 32, 34] The+ operator when used with lists requires that both the operands must be of list types. You Sannot add a number or any other value to a list. For example, into error : list + nunber list + complex-nunber Uist +string 4 The operator eoncatensies te lists 235 “a on Intersil compares individual elements of tivo lists, % you have read earlier. Consider following codes >marb False Doda False >>dena True atic for comparison purge, Dh (guned the typeof elements ra corporal vues eal ace True rar pett nt kav seme wanker of eens oad marching lat wih marching vuluce ae conser fea), that can be used for sequences’ comparisons but we are not that you perform with lists include joining lists, replicating lists just like you perform addition, literally +). The coneatenation 0 lists, joins two lists. Consider the example given belo, ‘and erates a ew fst Mant list has firstly elements of first list fst and followed by The + operators we to concatenate 4 tee intr Ett pel oc combined lis It following expression will result win conmutér SCIENCE WITH THON < ing exam seated whe anti Consider the following exampl enrgteatt pop Ast = (28, 22, 24] sey pop Asta +2 racobock (most recent ea10 2088)5 Fale “epyshell#az»", inet, 5 7 ) toss nae int") t0 ‘aera ‘can only concatenate 11st (not yoo Ista + "abe" 1 Last): Traceback (nost recent call 19st): Tile "epysheli#aa>", Line 3, in ceodul era on {not “str") to list Typetrror: can only concatenate 1ist 7.3.2 Repealing or Replicating Like strings, you can use (considering the same list Ist? = [1, 3, 5] ) — The + eneazr rept alist specifies = tex new i popistt3 | <————— umber of times and rea (2, 3,5, 1,3, 5, 1, 3,5] Like strings, you can only use an integer with a * operator when trying to replicate a list. 7.3.3 Slicing the Lists List slices, like string slices are the sub part of a list extracted. out. You can use indexes of list elements to create list slices as per following format : seq=L[start:stop] Lists . . * operator to replicate 2 list specified number of times, eg, When used with lists, the + ‘operator requires both the operands as list-types; and the * operator requires a list and an integer. The above iecment will create a Fist slice namely seq having elements of list Lon indexesstart starl+l, start42,...4 stop-1, Recall that index on last limit is not included in the list slice. The list ‘terisalistinitself, thatis, you can perform all operations on itjust Consider the following example ; est =L10, 12,24, 20, 22, 26, 30,32, 34) 92 Seq= 1st [ 3: -3] >>> seq (28, 22, 24] 99> seq 1) = 28 >>> set : » i ae Tarn 0 modify an emery ene roy at does bo cg e ae he list slice seyhs ats iniueyp like you perform on lists. re “Ustrstopy creates se Out of list Lwith elements falling between indexes start andst0P, ‘ot including stop. Seems 17ST MANIPULATION ; ot 237 cn ve boundaries, Forint wera instead, and the ren ay vaty eames items pve the stop given na lartbegs ind), Python simply retums the gleme It sin ata ere 8 that fall bet if Forexomple, consider the following : the list, yop Ist «120, 22, 14, 2, 22, 24, 30, 32, a4) pyo Ast [3238] 4 Giving per ins (20, 22, 24, 30, 32, 34) {ut bt hon ta de fo app Ast [-15 :7] : Inrange Formate te line (20, 22, 14, 20, 22, 24, 30) ~~ ising one tin uc ker, bet +—_ PEPE cerns from lst falling in range -15 onwards <7 yr 412, 3, 4,5, 6, 7, 8] ee degenerate 0.8 pop LL (2: 5] i irbex range is 0.8 and -7 =) 56) port [6:18] 3 One tints out of bounds 18] $s enor tr etums bls as por pve a poo Lt [18 : 26) <—__ - oa tiits ne out of ens + —~ Poston gives uo error ae rerum an enpey sequen as ta elenirt of E4 has index fling in rae of 10 0020 Lists also support slice steps. That is, if you want to e: tract, not consecutive but every other element of the list, there is a way out lee ~the slice steps. The slice steps are used as per following form: Ulstort: stop: step} creates a st te a slice out of list L with elements seq=L[startzstop:step] falling between indexes start Consider some examples to understand this. and stop, not including stop, Skipping step-1 elements in dolst between [20, 12, 14, 20, 22, 24, 30, 32, 34) = at astro £1022] Mite eer erent, ip element i in beesen Check eubing sce 2! - ‘ [, 14, 22, 30, 34] +-. ——_ ‘avy Jnl element, fe, akip 2 elements pods 11023] — (4, 24, 34] —— st stop § daly step is given as 5 That is, from eee Consider some more examples : Seq=1[::2] # get every other item, starting with the first , Seq= 15: get every other item, startingwith the sixth elenent, {.e., index ' je 30, 12, 12, 32, 24 25 16, ren SCENE WOHIPTHON id pie in felemohso py | ty aenes (015, POGrEM shou gi, calig every four efemen of i ‘ sun+ea, | print (a, end" ") Sample ran of above program is Hpsp print () . eh print ("Sun of elenents of slice 1:", sun) slice 1 | print ("slice 2") 6810 1214 ; | sun=@ sun of elements of slice 1: 50 | slice 2 fora in sie? : I Oe mea 1593317 i print (a, end" *) average of elements of slice 2:9 print () ' avg = sun /len(sle2) print ("Average of elenents of slice 2:", avg) Using Slices for List Modification You can use slices to overwrite one or more li s wil elements. or more list elements with one or as 0 more other . Following examples will make it clear to you : >>> L= [one", "two", "THREE"] >>> [2:2] = [ 8, 1] <—__ sien new values to ist sice ara (0,3, "mcery Ges Soir nt eich >>> Le["one", "two", "THREE*] >>> L[O:2] = "a" rk TAREE] A Ne what es apo In il the above examples, we have ass being assigned quence, i, a tc. 'B assigned must be a sequence, ive, list or stri ing or tuple et igned ne js 'w values in the form of a sequence. The values 74 wl caaper 7 UST MANIPULATION 239. <_ Forexample, following, assignment is also valid, po Ld = (1,2, 3] 299 LY TB) 0 6 me : por kd (1, 2,3, '6", "0", "ay £¥ Bat if you try fo assign a non-sequence value toa list sige such asa number, Python will give an error, fe 99 U1 [2 2) + 345 103 enunty, mv a eyuree Filewc. >) Line 2 Sn éncttules Ua [22] «345, TypeError: can only assign an iterable But here, you should also know length of the list it will simply omething. If you give alist slice with range much outside the ddd the values at the end es. vor bbe [1, 2, 3) >9 LA [10 t 20] » “abcd” *———_ sas ee re hough it slice fit ue ounide apd the kent. Now Pho wil append the Laer, > tothe endof tat 11 12,3, a", ~ wet, td") « 74 WORKING WITH LISTS Now that you have Mt 10 access the individual elements of a list, let us talk about how you can perform various operations on lists ike : appending, upslating, deleting ete, Appending Eleme s 10 a List You can also add items to an existing sequence, The end of the list. It can be done as per followin Coappenia( ite) Consider some examples poy Astd = [20, 12, 14] append() method adds a singleitem tothe format >>> Ist .append(16) o> Ista Median en eli eed tthe el ef exit lan [20, 12, 14, 16) «- feasting Updating Elements to o List To update or change an element of the list in place, you just have to assign new value tothe element's index in list as per syntax : ‘Utnde] © > Ast = (18, 12, 14, 16) a -. 1sta(2] «26 << $e stg net ee > Asta Display thelist 10 se the pated lst [20, 12, 24, 16) — ‘ COMPUTER SCIENCE WITH t ean be used to remove an ‘The del statemen” Tr used as per syntax iene 15 from 0 Lis Deleting Elements a from lists. 1 .n algo remove items Ir - sli You can ae ave al items identified PY t remove elemen' del List [ : Ist =[1, 25 3, 4, 5s 6» 70 8, 9 >>> Ast #[1, 2 weer in mare Dele elo , >a ttf] Ge oe aa gvdtrl Compare with i bore pees 18, 19, 20) [3,25 3, 4, 5, 6, Zo Bs 9p 38» 32s 33, 14 15, 16, 171 spveen indexes 10 10 15 in list >> del Ist( 28:15] +————— al al een se le so Ast ’ 20) [1, 2, 3.4, 5, 6, 7, 8, 9, 18, 37, 18, 19, If you use del only ¢.g., del Ist, it will delete all the elements and the list object too, ‘After this, no object by the name Ist would be existing. You can also use popl } method to remove single element, not list slices. The popt ) mettat removes an individual item and retums it. The del statement and the pop method do pretty much the same thing, except that pop method also returns the removed item along with deleting it from list. The popt ) method is used as per following format : List.pop( ) # index optional; if skipped, last element is deleted Consider examples below Soo dst =, 203,455, 6,7+8,9, 20, 11,22, 13, 16,25, [oho 16, 17, 18, 19, 20) ] While del statement can remove >>> Ist.pop() a single element or a lst-sice 28 from a list, the pop( ) an >39 2st.pop(16) Femave only single element, rot hn Uist slices. Also popt ) retruns the ; deleted element te The pop( ) method is useful only when you want to store the === = element being deleting for later use, eg, iteml = L.pop() # last item item = L.pop(o) # first item iten3 =L. pop(5) # sixth item Now you can use item|, ite ; item? i Gey and item3 in your program as per your requirement. yee Usts IN PYTHON - | 6 Progress In Python 7 ‘This PHP session works o: the opises : the objective of practicing List Manipulati ulation operators. aay bite) St ete Sometimes you need to make a copy of alist and you generally tend to do it using assignment, e.g., ae(2,2,3) Toying to mae copy of tat a bea inti put twill ot make B as a duplicate list ofa ; rather Just Hike Python ae dos, it will make label b to point to where label ais pointing to shown in adjacent figure, = ™ Inwill work fine as long as we do not modify lists, Now, if you make changes in any ofthe lists, it will be reflected in other because w and b are like al liases for the same list. See below : pr a=f1, 2,3] >>> bea poo af] =5 >a a is 3) ag See stb isso reflecting the >>> changed value of list a (4, 5,3) See, along with list a, list b also got modified. What If you want that the copy list b should remain unchanged while we make changes in list a ? That is, you want both lists to be independent of cach other as shown in adjacent figure. For this, you should create copy of list as follows : eb-([T TT) b= list(a) — Now a and b are separate lists. See below : >>> a=[1, 2,3] >>> b= list(a) >>> af] =5 >a (1, 5, 3] >o>b Now, list bis not reflecting the changed 12.253] 4 ale, List Bis adependent of list @ » ‘Thus, true independent copy of a list is made via list( ) method; assigning a list to another identifier just Creates an alias for same list. 75 UST FUNCTIONS AND METHODS Python also offers many built-in functions and methods for list. manipulation. You have already Worked with one such method len( ) in earlier chapters. In this chapter, you will learn about Many other built-in powerful list methods of Python used for list manipulation, Every list object that you create in Python is actually an instance of List class (you need not do anything specific for this; Python does it for you - you know built-in ), The list manipulation methods that are being discussed below can be applied to list as per following syntax : . method name> () NCE WITH F) COMPUTER SCIENC! THON , Se bra . > as List only (00 angle Brackets py erring! is Obl rit (e oither a it itera og gt » List with replace a raiftoningesaees 2 Haan ee ee re some useful built-in Tist mé | eran av ook | methods. fom the Fist. Ibis used 25 Per folloygg 1. The index method matched item “This function returns the index of first tus t format! 7 wpe tnd (ED . 7 For example, for alist L1 = [13,18 11, 16, 18, 14). cs a prursnees 2) re ee | : aises on value Error (see below) tem is not inthe list raises exception value Error (see below) | However, if the given item is not i List -index(33) Traceback (ost recent call lest) } 3”, Mine, in File “espython-input-60-038FcSbF2e5¢ / List.index(33) | Valuefrror: 33 is not Sn List | 2. The oppend method As you have read earlier Hist. 1t works as per following syntax : Co a7 that the append) method adds an item to the end of the Th List-append(>» colours, =([ ‘red, ‘green, ‘blue'] >99 colours append('yellow) Diteren * teil >>> colours, a ‘Sv the items gor add at the enlofthelie W , (red, ‘rect, ‘blue’, 'yellau’} Ms The appemi( ) does not retum the new list 1 | consider the following example : just modifies the original. ‘To understand bis i vo lst (1, 2, 3] ——__ 1 >>> Ist2= Ist. append(2) Toying 10 assign the rent of | bea < © ooo st mend) 10 anoter leg 1 wail doo Ist ee Sr 2 is empeyas apendy 4d mot return ay va tn ttt, oy Pri, bas the oe PENAL was Diference between append{ ) and extend{ ) popet 7 UST MANIPLIATION chon! 43, The extend method ‘Theextem!?) method is, also Used for adding multiple elements (given in the formof a list) toa list But itis different from apyper(). First, let us understand the working of extendf ) function then welll talk about the difference between these fie functions, The extend ) function works 38 pe Listextend(9t2=[7, 8] ‘ 2 aprent ) ear tke single acct — de> tl.append(18) AU > whether single item o sale sequence 1,3, 5, 10) eT Neti who wt give mip >>> tl.append(12, 24) largurients (0 oprendi). what harpens? Traceback (most recent cal} 1ast): File “", line 1, in ail ther roe tl.append(12, 14) — TypeError: append() takes exactly one argument (2 given) COMPUTER SCIENCE WITH Pravgy ttn the ryt ener ee Creras 1 ay it lice Ae mats lat ont eeren op tLappend(a2,24)) 4 to ve ist it wall show that mow Ut a. a etic data | [1, 3,5, 18, 2, faite >>> Jen(t2) 5 eno a site eet it j et ar { apo t2,extend(10) C scent call Last)? u Traceback (ost recent e011 1960 Fale “", he | t2.extend(10) ple 5. Yo Typetrror: “int object 1s not iters! ies >> t2.extend((22, 24]) eon pepe a rata con 2? aa obeet element tothe endof alist whe (7,9) a2, 14] oe extend} can adé argunen pp t3 = [20, 40] oo list’s all elements to the endef doo t2uextend(t3) <——— the list. T . pop t2 Jivihat After append! ) the length ofthe sf 17, 8, 22, 34, 20, 40] Sie, ll hate ey atte eit poo ten (t2) Serre Mernal velo ls now only after extend! the engh Hoi kas lenath of inserted it. - i ——— t @ iif = yi 4, The insert method “The iuseri( ) method is also an insertion method for lists, like append and extend methods, However, both append ) and extend{ ) insert the element(s) at the end of the list. Ifyou wantto | insert an clement somewhere in between or any position of your choice, both append Jant | i extend) are of no use. For such a requirement insert) is used. ‘ i ‘The inser) function inserts an item at a n position. It is used as per following syntax: } “List.insert( is the ii i itemise becdice © IM index of the element before which the second argument | Consider the following example | oo tle [a 'e, 'u] >>> tL dnsert(2, ') # inset element y at 4 c ati fn index 2. sect ‘ment insti ot index 2 eee 17: ST MANIPULATION function insert( ), we can say tha For sestisert (0,8) Will insert clement x at the front of the list ie, at index 0 (zero) qusteinsert(1en(a); *) will insert clement x at the end of the list ~ index equal to length of the list ; thus it is equivalent to listappend(x). “Ifindex is greater than Téntlist), the object is simply appended 1f,however, index is less than zero and not equal to any of the valid negative indexes of the list (depends on the size of the list), the object is prepended, i.e, added in the beginning of liste. for alist 1 =( 9", ’e', 'T, “u'l, if we do: “op tL Ansert(-9, *k*) valid negative indexes are -1, -2, -3, -4 poo tl ee eee er # List prepended with element ‘k? 5, the pop methed ‘ You have read about this method earlier. The pop )is used to remove the item’ from the list. Itis used as per following syntax : List.pop() # cindex is optional argument ~ Takes one optional argument aud returns @ value ~ the item being deleted Thus, pop( ) removes an element from the given position in the list, and return it. If no index is specified, pop ) removes and returns the last item in the list. Consider some examples : pootd CH #2, 0, a Ut) | >»rellel = t1.pop(0) + emore element at index ie, ft >oelel clorent and store i in elet ” Ae The removed element >oott [ate 9, Bi qu] List afer remoning fist eement >>> ele2 = t1.pop() >ovelez + feo der specified, i will move v the last element >»?tL Cat, "et, Pa] The pop() method raises an except Tist is already empty. Consider this >>> t2=[] #empty list >>> t2, pop() 4 Trying to delete from empry fist Traceback (most recent call last): raises exception File “", line 1, in ‘t2.pop() Indexerror: pop from empty list COMPUTER SCIENCE WITH what if you know the value of ion = given Fosition inthe Hist? Well, Pye jot know its ine ethod ) emoved, not remove( ) 7 | loment to be removed, je the en iter from the Hist. Its used ag thought it in advance an vronce of iver item fr Per i -The removel ) method removes 1 first oF 1d does WOE TELAT hy, \ ! following format : essential argumient ®™ $ tig : uae nthe list. Consider some examples. “Ustrenove ( Individual ter and cetuns | tl.remove('k’) while remove searches for ay, | Valuetrror: list.remove(x): xnot in list Hem, and removes the fist i 7..The clear method matching item fr ete This method removes all the items from the list and the list becomes empty list after this function. This function returns nothing. It is used as per following format, List.clear() For instance, if you have a list L1 as | ooo Le [2, 3, 4, 5] pom Lisclear( ) {rs more all he items from lst Lt. >>> Lt [J 4 Now the ison ry te of wt is remove fom the tse - ip is removed frorn she Tsk | Unlike del statement, clear()) removes , lear() removes , . Alter clear(), the list object still exists as an e1 SFY the elements and not thelist element. 2 mpty list. 1 e count method = This function returns the count in the list it returns zero, It is used as per ui count ( ) For instance, for a list L1 =[13, 18,2 >>> Lindo [16) 0, 10, 18, 23] 7: UST MANIPULATION p> og” 71 why aze Usts called mutable types 2 4 wtat are immutable counterparts of uss? What ate different ways. of creating sts ? What values can we have in a list? Do they all have to be the same type 2 «, Howare individual elements of lists are accessed and changed ? 4 How do you create the following lists 2 4 (0) [4 5. 6) ) [21 3) (0 [-9, 8. 5) (@ [-9. -10. -11, -12) (0.42) 7 Ifa = [5. 4, 3, 2, 1, 0] evaluate the following expressions: (2) 2fo] ay (9 alafoy] ( apt-1y) (9 ala 2) +1) ) & Can you change an element of a sequence? What if the sequence is a suing? What if the sequence is alist? 4. What does a + b amounts to if 2 and b are lists 2 ‘1 What does a * b amounts to if a and b ae lists ? UW, What does a+ b amounts to if ais alist adbe$? isa string the same as a list of characters ? 13. Which funetions can you use to add flerents to a list ? 1. Wat ic the difference between append ) itd insert ) methods of list? 'S What isthe difference between pop ) sad remove( ) methods of list? 'S Whatisthe atference between append) ay, Mi emtend( ) methods of list? a How does the sort) wosk? Give example. does list. clear( function do ? ee. 9. The reverse method The reverse ) ‘everses the items of the list. This is done “in place’, fe, itd et ise ides not eeateaew is The syntax to “Ust.reverse() > ~ Takes no argument, returns ni list ; reverses the list ‘in place” Ani oes nol return anything For example, >>>tt 2's," 'p') >>? tl reverse() >otd + The raed tit UP ay 3g, We) >>> t2=[3, 4,5] - >> td = t2.reverse( ) 2 — apap, >>>t2 (5, 4, 3] 10. The sor! method The sort( ) function sorts the items of the list, by default in increasing order, This is done “in place", ic, it does Rot createa new list is used as per following syntax: List.sort() For example, >>> t1l=['e, >>> tl.sort() >> th Sorte ise in defaule ascending order (ae i, py‘ 'a] G, "a, 'd, ‘P] Like reverse(), sort( ) also performs its function and does not return anything. To sort a list in decreasing order using sort( ), you can write: ">>> List sort (reverse = True) vf [KOEN ‘tbe able to sort the values ofa, dw tues ofa list if ieee number as an element, jon has 10 ordering relation defined for mplex numbers. { Enter list : Given list is the minimum elenent of the <9 at index 8 Enter list : (7, 23, Given list is : (7, 23 ‘the mean of the given list is : 15.364285714285714 rent cen rom aise ot teen » progam fd mii ci" aot e eval dnpue( enter 1S Jength = Len(lst) min_ele~ ist {0 min_index =@ for Lin range(s i gases] < minele? Sinete « 15t(3] mnin_andex= 4 : a motven List 4s: "> Nininun element of the & ae ,min_index) ength-1) * print( iven list 15 3") print("The: i print(min_ele, “at index [2 3, 46-2) 6-7 Be [2, 34 4y -2, 6 7 given Tist 15 ¢ Progiam to calculate mean of a given list of numbers Ist = eval(input(“enter List :")) length = len(1st) mean = sun=@ for i inrange(®, length-1) sun-¢=1st[i] mean = sun /length print("Given list is :", 1st) print (“The mean of the given list is ) mean) 11, 55, 13.5, 20.05, -5.53 1, 55, 13.5, 20,05, -5.5] Program to search for an clement in a given list of numbers. Ast = eval (input ("Enter List :")) length = len(1st) elenent = int(input("Enter element to for iin range(@, length-1) : ifelenent == Ist[4] : be searched for :")) print(element, “found at index" i) break else Helse of f print(elenent, ‘or Loop “not found in given list™) COMPUTER SCIENCE Witt along, with its index In the tg, Sgt MANPUIATION net mple runs of above progra ‘ noe 'BFAM are being given below pise [2 Be % UL, $5, 24 rE Srenent €0 Be Searched for 1322" 78 67) me Faynd at index S wer fist # (2) 8 9 12, 55, -ayy tel Grenent to be Searched for ; zy"? 78 671 oot found in given list i {e count Frequency of a ven element in alist f numbe of numbers, Ast = eval (input(“Enter 14st :")) length = len(1st) elenent = Ant(input (“Enter elenent :*)) count = @ for i in range(®, length-1); if element == 1st{ij; count +=1 if count == 0: print(elenent, “not found in given list") else: print (element, “has frequency as", count, "in given list") Sample run of above program is given below : emer Vist : [1, 1, 1, 2, 2, 3, 4, 2, 2, 5, 5, 2, 2, 5] Enter element : 2 2has frequency as 6 in given list 1] 77 Program to find frequencies of all elements of a list. Also, print the list of unique elements in the list | and duplicate elements in the given list. | tepan Ast = eval(input("Enter list :")) length = len(1st) uniq=[] # list to hold unique elements duph = [] # List to hold duplicate elenents count =i=@ while i < length : elenent = 1st[i] count =1 t # count as 1 for the elenent at Ist[1] feet for Jin rane if elenent ** count += elset hen ent prane(vexenent”» c20 sf count 723! ; I “nig, appenacezenen®) os wd(elerent) vast 5 dup1append(elen sacorat tists : found in u vhen element $5 else: dad : saa {) sotements ace not print(*ordginal 14st) 188) | steer a print(-unique elonents List", unia) Toe on pring(“buplicates elenents 235%" dup) : | 72,9 2D 2, Bu 4, Sy By Gr 7s 34 See Enter Vist = Elenent 2 frequency: 3 Elenent 3 frequency: 3 Elesent 4 frequency: 1 | cronent § frequency: 2 ] Elonene 6 fresuency: 1 | ev\ Elenent 7 Frequency: 2 Element 1 frequency: 1 Element 9 Frequency: 1 original Tist [2. 3s 45 5, 3y 6, 74 34 Sy 2) 7p Dy OM 2] unique elenents list [4, 6, 1, 9] buplicates elements list (2, 3, 5, 7] Usts IN PYTHON = II

[['few", ‘words']}, this is a list with one clement, a list. () True. As Oth element of L[2: 3} list isa list [“few”, “words”] which hasa member “few" init. (¢) True. £{2] returns the list [‘few’, ‘words'], “few () L[2] = (Few, words’) an clement of this list. 12] U1] + U2) = [are’, ‘2, “fev, ‘words! 5. Lisanon-emply list of ints, Print the smallest and largest integer in L. Write the code without using a lop. Solution. length = len(L) Lesort() print ("smallest :*, print (“largest » L[@]) Lpength-a}) 7 LIST MANIPULATION ite the most appropriate Tist method to perform the following task. (a) Delete a given element from the tist, () Delete 3ril element from the list. (@) Addit an element in the end of the Hist, (d) Add an element in the beginning of the list. (2) Adi elements of list in the end of atist gatution. (@) Femove() (b) pop() (c) append) (d) insert() (¢) extend( ) 4, Given alist of integers, Ly write code to add the integers and display the sum. solution. pos = @ # start of list sum = @ # initial sum while pos < len (L) : # loop through entire list sum = sum + L(pos] # add current item to sun pos = pos +1 Hf move to next item in ilst print (sum ) # the answer , Given a list of integers, L, write code to calculnte and display the sum of all the odd numbers in the list. Solution. pos =@ # start of List sun=0 # initially no sun while pos < len (L) : # loop through List if L[pos] ¥2==1: # this is an odd nunber sum = sum + L{pos] # so add it pos = pos +1 next item in List print (sum ) # the answer 9, Examine the following code : Y nunlist = eval(input( "Enter list:")) pos = 0 odds = evens = @ Jength = len (num list) while pos < length : if numlist(pos] %2 == 0: evens = evens +1 else : odds = odds +1 Pos = pos +1 if odds > evens : print ("Balanced oddity") (2) What is this program calculating? (b) What does the program for thelist (1, 5,2, 3, 6, 6,9]? (©) What does the program print for the list |2, 5, 2, 3, 6, 6, 9]? How can we fix this ? Solution. (2) The given code is checking whether a list of numbers is ‘mostly odd’ — ie, whether there ate more odd numbers than even numbers in the list. (b) Balanced oddity (€) The code prints nothing. This if odds > evens : print ("Balanced oddity") else: print (“Unbalanced oddity") because there is only one print statement, the fix is : COMPUTER SCIENCE Wit} if they have al least one member py for le sake ofthe exercise, write jy using, sans “Overlapped” 10. Given tay fists, write # program Hat ri nero bul otherwise prints “Sqnarated™, You may use the tion. . oe = eval input("énter 14st] :°)) Lista = eval (input ("Enter ist2 :")) lent « len(1ista) Jen2 » len(1istB) for a in range(lenl) : ele = listafa) ifele in listB : princ(“Overlapped") break else : , print("Separated” ; LL Write a program te find the second largest number of a list af munbers. ‘loop ends normally, not because of break © Solution, Ast = eval (input("Enter list :")) length = len(1st) bineese = secondbiggest = 1st[@] # though logically not fair for 4 in range(1, length): Af Ist[i] > biggest: secondbiggest = biggest biggest = 1st[i} elif Ist[i] > secondbiggest: secondbiggest = Ist[i] print(“Largest nunber of the list :", biggest) print("Second Largest number of the list :" secondbiggest ) 12. Write program that inputs ats of numbers aut shifts all the zeros to right and all uon-zero mumbers toe, of the list. Solution, Ast = eval(input(“Enter list :")) Jength = len(1st) end = Jength-1 print("Original list : ", 1st) iro while (4 <= end): ele = Ist[i] ifele=0: for j in range(i, end): Ast[i] = Ist[jsa) else: Ast[end] = @ end = 1 4¥ Istip! i 4 # if after shitting, a Consecutive @ shifted to current place Print("zero shifted : ", Ast) en tn Che 81. Invoduction 82 Creating and Accessing Tuples 82. Tuple Operations 84 Tuple Functions and Methods 81 INTRODUCTION The Python tuples are sequences that Jeamt in earlier chapters that Python tuples of a tuple int place ; Python will create 3 fr tuple, Tuple is a type of sequence like string lists are mutable but strings and tuples are This chapter is dedicated to basic tuple man creating and accessing, tuples, various tuple built-in functions. are used to store a tuple of v Jues of any type. You have are immutable ie, you cannot change the elements 1 uple when you make changes to an element of s but it differs from them in the way that and Ti iment ailation iy Python. We shall be talking about operations and tuple manipulations through some COMPUTER SCIENCE WITH) 8.2. CREATING AND ACCESSING TUPLES on “round brackets, ¢.-, following are me empty tuple oO a tuple with nomenbery le of integers 25 ) tuple of nurbers (integers and floating point) 1, 2.5, 3.799) ce ‘e,'e) #tupleof characters (3,1, , 3.5, zero) # tuple of mixed value type 0 # tuple of strings as Cone’, ‘Tho', ‘Three’) ‘Tuples are Immutoble sequen: Before we proceed and discuss how to create tuple oe a a ees Pion = that must be clear is that Tuples are i mutable a ners token non-modifiable) fe., you cannot change elements of ofa tupl $ nig 8.2.1 Creating Tuples Creating a tuple is similar to list creation, but here parentheses. Thal is, use round brackets to indicate the items by commas. For example : you need to puta mumber of expressionsin | the start and end of the tuple, and separate (2,4, 6) abe’, ‘deF) (4, 2.0, 3, 4.0) 0 Thus to create a tuple you can write in the form given below : T=() T= (value, ...) This construct is known as a tuple display construct. Consider some more examples : 1, The Empty Tuple The empty tuples (). Itis the tuple equivalent of 0 or", ‘You can also create an empty tupleas: T= tuple() It will generate an emply tuple and name that tuple as T. 2. Single Element Tuple Making a tuple with a single clement is trick brackets, Python considers it a value only, mo t=(1) vont a 00 raed 50 1. Fae etl oie eresian a heer y tent tape ¥y because if you just give a single element in rou eg. tuples lon . at tuple contains many formed by placing a elements, then t tuple of | acta © enter such [@=Pressions in parentheses, ples, YOU c0” Spt it across several ine 8 given aon a 3 sars= (8,2, 4, 9,36, 25, 35, 45, 64, on 4 256, 289, 324, 361, 499 00, + 121, 144, 169, 481,84, 520,59) cS 69, 196, 225, Notice fhe opening parenthesis and losing parenthesis PPear just in the beginning and end of the tuple. 4, Nested tuples Ifa tuple contains an element which is a tuple itself then itis called nested tuple e.g., following is anested tuple : t1=(1, 2, (3, 4)) The tuple tI has three elements in it: 1,2and 3,4). The third clement of tuple tl isa tuple itself, hence, t1 is a nested tuple. ing Tuples from Existing Sequences You can also use the bu ilt-in tuple type object (tuplet )) to create tuples from sequences as per the syntax given below : T= tuple() ‘where can be any kind of Sequence object including strings, lists and tuples. Python creates the indiv Sequence. If you pass in Conside idual elements of the tuple from the individual ele: another tuple, the tuple function makes a copy. * following examples : ments of passed >»; >»; Ch ET tepec helio) Tuple wis crated from another sequence «a sing “hello” ae 4 te generat iia elements fom the ‘ntivihas! 10) >>Ls EW, ete, ey] »>t2=tuple(L) Tupte teil nat sn i ae crated individual elements from the é inddua ements of the passed list L 7 . 1 COMPUTER SCIENCE WITH PHO c raracters or single digits via on sing apes fs Norton | 08 You ean use this method of creates *e input. Consider the code below * on ; exe tuptec tnputenter tuple e76r= ee : ef cer tpl elenants 234567 sundae eterscns of tuple Ener uP Sn ge carter (2,38) S'S : scyou not put parenthesis, it will create a tuple Using See, with tuple() around input) even it Yost or Paonly used method tO input tury s jndividual characters as elements. But eval(inpul0) as shown below + tuple = val input("Enter tuple to be added: » print ("Tuple you entered :*, tuple) when you execute it, it will work somewhat like = enter tuple tobe added: (2, 4, "a, "bik31"» [3.4]) Tuple you entered : (2, 4, "3", “nIkI2", [344]) os o sure e the tuple ek If you are inputting a tuple with eval(), then make sure to enclose ple elements in ! parenthesis. ; : Prease note sometimes (not always) eval() does not work in Python shell, At that time, you can nun it through a script too. 8.2.2. Accessing Tuples Tuples are immutable (non-editable) sequences having, a progression of elements. Thus, other than editing items, you can doall that you can do with lists. Thus like lists, you can access its individual elements. Before we talk about that, let us learn about how elements are indexed in tuples. Similarity with Lists Tuples are very much similar to lists except for the mutability. In other words, Tuples are immutable counter-parts of lists. Thus, like lists, tuple-elements are also indexed, i.e, forward i indexing as 0, 1, 2,3... and backward indexing as ~1, ~2, ~3,,.. [See Fig 8.1(@)] fuptet = (-0",'6' 7, 01") Fowndbdeing>0 1 2 3 4 OH teplot| a etlou Totpet ta 472 Satan 9 wnat th tuplet -2) (0) Tuple Elements’ two way indexing Shapes { Each of the individuat item: red i 459 somawhere a nme 2 re egiduel tems ofthe tuple are. sto Fi Sue 8.1 (2) How tuples sre intemal organized ql Hema ime, y US ours its individ in ups @ Indexing and Slicing Ti returns the item at index i mae eB the Tli: {201 retums a new tuple a index j. Just like lists, © Membership operators. B Both ‘int work for other sequences, Thatie eed ROl it not in does the opposi That is, in tellsifan cement proce athe icon PPosite element is present in the tupl and tuple or not an first item has index 0), Ing the obj Objects between i and j excluding index j, 'uple containing every ym index j to j, excluding ing nith item fro i Concatenation and Replicati ‘plication o end of another. The * Laake inate The een opera The + operator adds one tuple ee ey cheer Rss tuple We sal e aig sou ese two 3 = Tuple Operations ‘ ™ sessing Individual Element Acct Is ‘As mentioned, the individual elem v ¢ ial clements of a tuple are accesses Fe ochete, Consiter the folloming ex re are accessed through their indexes given in poo vowels = ('a', "ey "S,'0', Ut) : >>> vowels [@] ‘While accessing tuple elements, IW you pass ina negative index, >>9 vowels [4] uw 59> vowels[- 2] Python adds the length of the : tuple to the inden to et : element's forward index. >>» vowels[- 5] © Sas “ if you passin a negative nde, Python adds the length of the tuple to the Recall that like strir Pat is, fora 6etement tupleT, TI-S}willbe intemal ‘computed as: index to get its forward inde TI-S+ 6]=T11], and soon. many ways yet there i. an important differnet in iitable, while lists are. You cannot change individual Spat ists allow you 10 40 50 lid for lists (BUT not for u rape Fruples are similar to ists In ey war the Indes sink Diference from Lists fe similar to lists in es are not Mm Although tuples ar mutability of the two. Tup! clements of a tuple in place inti fully ¥ ateme ist Land have ah Thatis, following s tuples), That is, if 3 L[i] = element rd accessing we is VALID for Lists. BUT (meni at ne a afer for Lists Mote sore tat tiles i} = process each Sten here i yarate lines : For example, following loop shows eae iter of a tuple Tin sep Feces yet) nq fora in’ } print (Tl2]) | The above loop will produce result as = A | , | el } a | How it works { The loop variable a in above loop will be assigned the Tuple elements, one at a time. S| Joop-variable a will be assigned ‘P' in fist iteration and hence ‘P’ will be printed; in second iteration, a will get element ‘y’ and °Y’ will be printed ; and so on. 1 {| Ifyou only need to use the indexes of elements to access them, you can use funetions range) , | and fen{) as per following, syntax : . i for index in range(1en(T)): 4 process Tuple[index] here \ | Consider program 8.1 that traverses through a tuple using above format and prints each itemet a tuple L in separate lines along with its index. 8.1 Program to print clements of a tuple (‘Hello’, “1 r nts of @ tuple ("Hello’, “Isn't, ‘Python’, ‘fun’, «2° fines along | ‘ \ , with etement’s both inden (postive ond negate), ” > 2") Im separate | | Trogram Tet 'tsn't, 4 i = (Hello, "Isn't, ‘Python’, *furt, "2" i Jength = len(T) : | fora inrange(length) : | print (‘At indexes’, a, ‘and ', (a- length), ‘element :', Ta]) i At indexes 0 and -5 elenent : Hello | At indexes 1 and -4 element Isn't At indexes 2 and -3 element Python | At indexes 3 and -2 element : fun At indexes 4 and -1 element : ? Now that you know about tuple traversal, let us talk about tuple operations. a perations. at atime s, | ed; in seed tions ray goon TURES a gg. TUPLE OPERATIONS 5 ‘The most common operations that tuples. In this section, we are goj You perform with tuple ng to tak about the ee MeIUEE olning tuples and slicing 3.1 Joining T uples Joining two tuples is very easy just lke y concatenation operator, when used with td reste ition: literally 2). The + operator, the Consider the example given below : 'uples, joins two tuples. ooo tpl = (4, 3, 5) >>> tpl2= (6, 7,8) >>> tpli + tpl2 ——— peo eosatenas mo pk er: sod crater ne te As you con see that the resultant tuple has firstly elements of first tuple [st? and followed by elements of second tuple Ist2. You can aisojoin tivo or more tuples 10 formanew tuple eg >>> tpl = (ie, 12, 14) >> tpl2= (22, 22, 24) 92, tpL9 + (38, 32, 36) ‘The + operator is use! w concatenaie po>tpl=tpli+tpl2+tpl3 thre iia wples 10 get 2 ne ooo tpl Sct! wpe (10, 12, 14, 20, 22, 24, 30, 32, 34) The + operator when used with tuples requires that both the operands must be of tuple types. You cannot add a number or any other value toa tuple. For example, following expressions will result into error: tuple + nunber tuple + complex-nunber tuple + string tuple + List ERROR < WN Consider the following examples : = See err geet when wmting Sid hawt ule atid le >>> tpl = (10, 12, 14) poo tpl +2 cal last): Traceback (most recent Line 1, in File "" tpli2 Typetrror: can or > ‘tpl + "abe" Traceback (most recent ¢é File “epyshelLead>", Line, tpl + "abe" Typeerror: can onl} nay concatenate tuple (not “int") to tuPle a} last! in «nodule? y concatenate tupte (not “str) f° tuple computer SCIENCE WITH PYTHON 2g: smotimes you need to concatenate a (U) wee ple (say tpl) with another tuple containing only ong if you write statement like ¢ element, In that case, po tpl + (3) wn will return an error like : tt Traceback (nost recent call las File “epyshelli4s", Line 1, in «nodule? tuple + (3) saint” 2 typeErrort con only concatenate tuple (not “int") to tuple ‘The reason for above error is that a number enclosed in ()is consicered number only. To make Festaple with ost one clement, just add a comma ater the only element ie. makeit 3). Now Python won't relum any error and successfully concatenate the two tuples. >>> tpl =(10, 12, 14, 28, 22, 24, 38, 32, +34) Sint tome tpl e “pa tpl + (3,) 4 (20, 12, 14, 20, 22, 24, 30, 32, 34, 3) Repeating or Replicating Tuples Like strings and lists, you can use" operator to replicate a tuple specified number of times, ¢g, if tpl1 is (1, 3, 5), then js tpt +3) ¢_——— The * orator repos tuple speis eed Ley ‘mumber of tes and eats tew ple” 8.3.2 Slicing the Tuples Pie [When used with tuples, the ke list-slices or string slices are the sub parts of ; reallBons ‘operator requires both the ia racted out. You can use indexes of tuple elements ‘operands as tupletypes; and | fe slices as per following format : the * operator requires a if and an integer | ‘seq=T[start:stop]. = = The above statement will create a tnple slice namely s le T on indexes ate a tuple slice namely vi i fat dart ain p eq having elements of tupl i p-1. Recall that index on last limit is not i i e slice The tuple stce is a tuple in itself that is y riled pahepmenesensaie cntuples ein iself that fs you can perform all operations on it just like you perform Consider the following example : >>> tpl (18, 12, 14, 20, 22, 24, 38, 32, 34) > $eq = tpl [ 3:-3] * >>>.seq (26, 22, 24) Beg, ig: TUPLES yornormal indexing, if the resi jon raises an IndexEree ni poundaries instead, Vand theres goon. Si le the tuple, a a ult wpe Msnanpen et Pe septs ore * Python sim ‘OP given bey. thot fall Between specified penn "PY retums hee 01 ies, i ns the elemen| itany, nis >> tpl =(10, 12, 14, 29 +14, 20, 22, wn [3:30] 32, 38) Ging ure (28, 22, 24, 38, 32, 34) yin litt ay bod he sof he wpe but tel [15-7] lene ft ak fling rong © (20, 22, 24, 20, 22, 24, 39) Tuples also support slice st other element of the tuple, there range OU following format : Giving ‘ant to extract, not consecutive but every th vay ere is a way out ~ the slice steps. The slice steps are used as per seq=T[start:stop:step] Consider some examples to understand this, 22> tpl (2, 12, 14, 28, 22, 24, 30, 32, 34) EZ] intl at mat te in berger. Check ring poo tpl (a: 1 | (20, 14, 22, 30, 34)* pop tpl? 20: STS padecoy attr es 2 tt (14, 24, 34) goo tpl: 3] Nesta tion, Oa ei a 8 (ap, 20, 38) Tats fom the ein le, ik very Bl element ft pie Consider some more examples: seq=T[:: # get every other item, = vt every other item, seq=Tl Fe ener, Inox a sixth element ators with tuple slices too. For [NOTE al You can use the + and * ope 5, as (2,4,5,7-8:9 lr Istsartz stops stp creates 2) starting with the first starting with the example, i » namely Tp has values 2 ample, if a tuple namely TP vemomarems 2,34), then : sone eet mio a See andthe fll te ments between yo Tp 12:5] *3 a (5, 7, 8, 5, 72 8: 52728) i 4 a + operator has da! the doo TpL2iS] + (3s 4) je en est (5, 7, 8 3,4) COMPUTER SCIENCE WITH PTW | write code with loops for it having to I= etc. wo tuples withou ye mee fet . 7 P oneno er of two pls AIAG al the comp tuples 3 OP ie Consider following, Com es read earlier pat you have rales thot ¥ yar (23) pode (243) praeed Troe Ss TW LN a ) Fo ef lesen al racing alu val a ed flo ith rscing PI Se eed egal sorce (24 past False porard False pode (2.0, 3.0) podra False pordeea Troe vere (2, 3,4) Troe You can refer to table 7.1 that discusses non-equality comparisons of two sequences. Elements in tuples are also compared on similar lines Creating a tuple from a set of values is called packing and its reverse, ie, creating individu ‘Values from a tuple’s elements is called ‘unpacking. Unpacking is done as per syntax : svariablel>, , net of Where the number of variables in the left side of assignment must match the number ‘lements in the tuple. For example if we have a tuple as : 01,2, 8) she levgth of above tuple tis 4as there are four elements in it. NOW to unpack it, we can writ Ky ret SA ties neve chs the vrisls on LTS im porrthesis. I wil give you same reat. s eo Pere thon will now assign each of 4 gssignment operator. That is, yo a the elem: ents of tupk P 7 le to the vari | gomewhat like : an now indivi oat ‘0 the variables on the left side of : '¥ Print the values of these variables, print () print (x) print (y) print (2) The above code will yield the result ae = ‘i : 2 w v As per Guido van Ros i the creator of Python language — “Tuple unpacking requires that the list of var ist of variables on the te Sea f variables on the left has the same number of 1 Deleting Tuples ‘The del statement of Python is used to delete clements and objects but as you know that tuples are immutable, which also means that individual elements of a tuple cannot be deleted, ic. if ||| you give a code like : oo del t1(2] Then Python will give you a message like : | Traceback (most recent call last): | ", line 2, in File "cipython-input-83-cad7b2caBee3> del t1[?] tuple’ abject doesn’t support Aten deletion complete tuple with del statement as = TypeError: But you can delete a del For example, poo th = (5) 75 34 9 12) >>> tr (5, 7, 3, 9, 12) >>> del ti Ae >>> print (41) st)? Traceback (most recent an 730070739? ine 1, in enodule> File “eipython-inpyt print (t1) _ COMPUTER SCIENCE WITH pypaa. THODS a e sions and methods for tuple manipulation, Yo, any builtin oe Hon) In earlier chapters: In this section, you wy Mt he ram, uch met — ‘worfull tuple mel ‘yseful built-in (Upl hhods of Python used for tuple mani ae Je manipulation methods. other bull oT Ton) t808 ‘This method returns 1 Syntax? | ren etuple>) Tes tle name a argu th of the tuple, be the count of elements in the tuple, J length of : ip auf and retrrus an integer Example fo enployee = (John, 10008, 99> Len(enployee) a = he nt) rears the count of ele 2: The mox()) method ‘This method retums the element from the tuple having maximum value. 24, ‘Sales') tuple Syntax: ‘max() = Takes tuple maxima Example : >>> tpl = (10, 12, 14, 20, 22, 24, 36, 32, 34) > max(tpl) 4<——_ 3 Maxima value from ple tpt» med >>? tpl2 = ("karan, “Zubin” >2>max(tpl2) ‘obi’ «———__ Mavinwom value from tuple tp és retunted () 01 lists too to find maximum element {rom a Je that al) i! | | _ Please not | applied on sequen pepe vi | Contains values ofsame tyne ees ete ill return a maximum val je ONLY TF the see | will give you an error at ee your tuple (or list) contains values of different datatypes = f) i © >a, a that mixed type comparison is not possible : (alll * (1, 2.5, "1", (3, i >>>max(ab) (4), (3,4) ) Ht Traceb; a ‘ack (ost recent cal) last): File “", line 1, in ig TUES. >>>ab= ([3,4], Traceback (most p, Cet ca 1 File ") = = Takes tuple mane as a et ‘ple name as argument end retums a "5 aM abet (the element with i ut wit ima ved i >>> tpll= (10, 12, 14, 29, , 12, 24, 20, 22, >>> min(tpl) 74,38, 22, 34) i | ne Masiorurn vate from tape tis earn) iL] >>> min(tpl2) >> tpl2 = ("Karan", "Zubin","Zara", | pl2 = ("Karan", "Zubin","Zara", ana") iN" | 1 An riun re | are trad HH Like max( ), for min( ) to wark, the elements of tuple should be of same type, H Hy 4qThe index( ) method The index( ) works with tuples in thesame way itworks \sithlists-Thatis tretumstheindexof ||| an existing, element of a tuple. His used as : | ‘ctuplenane> . index (>> t1= [3 4, 5, 6-8) | “nae mit? 144 5 a (99? t index (5) ; ypes tnenstt 2 valuetior exception \} But if the given item does not jnjeet in 3 giver sSP80—° aber element eb mae 8 The count( ) function , The count( ) method returns tht (istftupte). You can use the count( rear fe count of 8 TN jowing Example? 9, 33,752) poo te (2a dy pp9 ta eoune(2) por ta.count(7) 2 poo tiecount (22) 2, 50 77 42 89 3 ara element it in Tuple, ives 0 (zero), 62 Tha tuple( ) method id to create tuples from different This method is actually constructor method that can be user “types of values. Syntax ‘tuple(esequence>) = Takes an optional arguinent of sequence is eraply tuple pe; Returns « tuple. = With no argument, it retun Exaniple = © Creating empty Inple © Creating a tuple from a list 90> tuple) >> t= tuple([1,2,3]) oO pot © Creating tuple from a string (12,3) >>> t= tuple(“abe") Dont (2,8) AS you ca tice Pyt ‘ tuple Butone th that, Python has considered only the key’s of the passed dictionary to creat® yee ont thing that you must ensure is that the tuple( ) can receive argument of sequere® ;, ’e,, either a string or a Ii ena dieti an error. See below : 1g or a list or even a dictionary. Any other type of value will ead! >>> t= tuple(a) NOTE aad Traceback (nost recent call last): le “cpyshelli#1>" With tuple), the Rem t= tuple(1) eae teen eee ee ie sequen aa a string ora lst 3 dT! 1 : . ‘yeeError: ‘int’ object is not iterable ie lupe ) and tisi( Passed sequence, Jan Possible, THe ae constructors that let you create tuples and lists respecte Following eat can be exploited asa trick to modify tuple, whieh one formation box talks about the same. hat et) iy les called immutable types ? pot are mutable COUNteNpaTtS of eyes can we hove in a tuple ? pothey all have to be the same type”? ow are individual clements of tuples accessed? tow do you create the following tuples ? () (4, 5, 6) @) (-2, 4,3) (9 (-9, -8, -7, -6, -5) () (-9, -10, -11,"-12) fe) (8, 1, 2) a= (5, 4,3, 2, 2, 0) evaluate the following expressions : @) ao} etal Anand", 35000, 35, “Admin") ©) aft} : . © afatey) (anand , 35000, 35, ‘Adnin') (@ afat-1]) (© afafata{2}+1J]] Gn you change an clement of a sequence ? What if the sequence is a dictionary ? What if the sequence is a tuple? What dees a + b amount to if a and b Be tuples ? >>> 1st 1] = 45000 Whar does a + >>> Ist. b b © tuples 2 mount tows and ['Anand, 45000, 35, ‘Admin’) that a toyte and a 7) amnunt te it a a 3. Create a tuple from the modified list with wpleQ, hyecttiAg the same as a tuple of >>? tpl « tuple(1st) acters > >>> tpl. pica have an integer, a string, a ['Anand’, 45000, 35, ‘Admin'] a tupie 9 and a tuple of strings ‘Tuples are immutable: t ‘Counterparts of lists. If you need to modify 'e contents often of a sequence of mixed types, then you should 60 for lists only. However, if you want ta ensure that a sequence of mixed types is not accidently changed or modified, you go for {uples. But sometimes you need 10 retain the sequence as tuple and sill need to modify the contents at one point of time, then you Can use one of the two methods given here. (0) Using Tuple Unpacking Tuples are immutable. To change a tuple, we would need to first unpack it, change the values, and then again repack it: tpl = (11, 33, 66, 99) 1. First unpack the tuple : a,b,c,d= tpl 2, Redefine or change desired variable say, © c=77 3. Now repack the tuple with changed value tpl = (a,b, c,d) {b) Using the constructor functions of lists and tuples i.e., lisi( ) ond tuple( ) ‘There is another way of doing the same as explained below : 1, Convert the tuple to list using list() : >>> Ist = List(tpl) >>> Ist (Anand, 35000, 35, ‘Admin’] 2. Make changes in the desired element in the list Isn't the trick simple? © . ~ Progress in Computer factical component-book Pleose check the rein ahora in PriP 8.1 under Chepler & otter) Science with Prin ically doing it on the compuler- povteee . theend of eur chapter. Let us quickly revise what Wehaveteingy With this we have come to far. Let Us REVISE = ‘ples are immutable sequences of Pyton i, yu cannot change elements of a tuple In place The empty round brackets ie.,() indicate an empty tuple | ‘ples index thee cements just lke strings or fists, Le. bo way indexing . I 4 Tuples are stored in memory exactly lke strings, except that because some of their objects ore larger tha abe they store a reference at each index instead of single character as in strings. ‘¢Tuples ore sinilor to strings in many ways like indexing, slicing and accessing individual elemenss exbdqet * immutable just like strings are. \ Function lea(L) returns the number of items (count) in the tuple L. | ‘Membership operator in tells if an element is present in the tuple oF riot and rot in does the opps. | ‘& The + operator adds one tuple tothe end of another. The * operator repeats a tuple. i 4 Tuple slice is an extracted part of tuple; tuple slice is @ tuple in itself. ‘ Tistartstop] creates a tuple slice out of tuple T with elements falling between indexes start and op rte I stop. i % Common wple manipulation functions are : ten( ), max(), min( ), and tuple( ). 3 \ Siiied Problems w How are tuples different from lists when both are sequences ? Solution. The tuples and lists are different in following ways : © The tuples are immutable sequences while lists are mutable. ® Lists can grow or shrink while tuples cannot. 7 ries: oo A 1 say that a tuple iS an ordered list of objects ? nyu = pes OF uple is an ordered list of objects. This is evidenced by the fact that the objects can ue stom a ough the use of an ordinal index and for a given index, same element is retumne vase 3 time ow coe is trying to create a tuple with a single item. But when we try to obtain the length of the tuple ellen es error. Why? What is the solution ? 3. pytiion sie po t= (6) poo ten(t) qraceback (most recent call last): File “epyshell#8>", line 1, in cmodule> len(t) aypeError: object of type "int’ has no len() solution. The syntax for a tuple with a single item requires the item to be followed by a comma gs shown below tera") Thus, above code is not creating a tuple in t but an integer, on which lent ) cannot be applied. To crate a tuple in t with single element, the code should be modified as : oop t= (6) >>> len(t) What is the lengtit of the tuple shown below 2 t= CCCI, 14°, "e), ', 2), 'e 3) Solution. The length of this tuple a careful look at the theta a wet, 33 = t2, "a", 2 t= (t3,"e", 3) Gn tuptes be nested? 3 because there are just three elements in the given tuple. Because ‘0 tuple yields that tuple ¢ is made up of : Solution. Tuples can contain other compound objects, inclu Hence, tuples can be nested. i lists, dictionaries, and other tuples. Ke © Given a tuple namely cars storing car names as elements : Toyota’ ‘Honda’, "GH", ‘Ford’, ‘BHi", “Volksuagon", “ercedes', *Ferrai*, "rite a progrann to print names ofthe cars in the inde range 2 to 6, both inclusive, The output showtd also *Porshe*) include the index in words as shown below : One Honda Two GM Solution, Cars w (x . ne (Toyota! Honds','GM, Ford "SM, Volkswagon Seber «Zero, “On: "xin range(2,7: Print (Nunber[x], ears{x]) a ‘Mercedes’ Ferrart','Porshe) ey “Two", “Three”, "Four", "Five", "Six", "Seven", “Eight, "Nine™) COMPUTER SCIENCE WITH Py ay rents Replace fist four element flit nit sth sine cleric fis for fis eT, 2,72 PD Tacrisel nr ake ts exfore al afler Une Ht Is modifi, Nig | gl Co Gicen a Tet single s! ee four eee ” Se aN ce ery ners, ensne “ort “eupte] a Theta, Senet ar ro rane ‘caefore unpacking She | yw? pete a aL EIT gen) 5 oer fo}, CLT, Ud Le . ; e prams (9 seston ftce change He square brackets of ccond Fe fo round pg “ge antheunner olf press es if : reg, te) ames? sult he the impact of this change pater waltzen intoerror because now Lisnota lis but tuple (because Brakes chang tuple is immutable, hen ignments are not possible. 4 » So, Python will display like 2 Before Unpacking the list is (hello, ‘there’, ‘are’, ‘sone’, ‘numbers’, ‘coming, “front, “tuple’) Traceback (most recent cal] last): . File °C: /Python36/Pythonliork/prog.py", line 5, in «modules * 4 Ufo], ft], L¢2], 113] =T : Typetrror: ‘tuple’ object docs not support item assignment 9 Write a Python function secondLargest(T) which takes as inpul w tuple T and returns the send lye element in the tuple, You can use any of Uie standard Python functions to obtain your result. 7 Solution T= (23, 45, 34, 66, 77, 67, 70) maxvalue = max(T) ‘ Jength = len(T) secnax = 6 ; for 2 in range(length) : ; if secmax < T[a] < maxvalue : . secmax = TLa} 2 print ("Second Largest value is :", secmax) 4 t , . 5 i . 10. Write a function getPowers(x) that returns a tuple containing x, x2, x and x*, Read fice integers fe 1 user, and for each integer read, print that value raised to the powers 2, 3 and 4. , Ype | Solution. | for n in range(S) : x= int (input ("enter Number :")) T= (x, x02, x93, x14) print (number, “raised to powers 1, 2, 3, 4 a1 2. Introduction 92. Dictionary ~ Key: Value Pairs 93. Working with Dictonanes 94 Dictionary Functions and Methods INTRODUCTION You must have realized that Python offers many different ways to organize collections (é bunch of values in a single “variable”) of data items, such as strings, lists, dictiona Of these you have alre, ies, tuples ete. dy worked! with strings, lists and tuples in previous chapters. Now is the line to work with other collection types. So, in this chapter, we shall be talking about dictionaries, In this chay pler, you shall be teaming about how data-items are organized in a Python dictionary, ‘ how you can access items from a dictionary, various operations that you can Perform on a dictionary and various related functions and methods, a a compute SCIENCE WITH PYTHON . ev : PAIRS coe ealled a dictionary. Dictionag, 92 bycronany =KEVNALUE PA isa voy verse pect Rather than having om yailt-in Python data YPC Thon, but wl x ries in Python hay. Among toe a 0 ee oe tr ic eee ey ae simply are dotaitem (ust KET ges are acolestion O° hepa. Sesociated with na Fo That is, Python diction jetiouaries you can search for a toy be aed Kit oa a there isa mins eee cords) and associated values Gist ize FG i eee Exgist ee hat essocinle ApETA TROT DET Se neon tse ere aa ot nt seconati, ar have to know the Key to find the element eval pats that mack keys to values. in the dictionaries. ” ‘All this will become clear to you w following sections. hile you go through 9.2.1. Creating 0 Diclionary 7 ; ‘To ereate a dictionary, you need to include the key value pairs 3m curly braces as per following syntax: value>..+ } edietionary-nane> = { , , "Line 1, in «module» dict3 = {[2,3]:"abe"} TypeError: unhashable type: ‘List’ oe IMPORTANT The above error TypeError: toassign a key with mut. unhashable type always means that you have tried | able type and Python dictionaries do not allow this, 422 ‘Accessing Elements of a Dictionary _ While accessing elements from a dictionary, you need the key. While in lists, the elements are denen, tough their index ; in dictionaries, the elements are accessed through the keys defined in the key:vulue pairs, as per the syntax shown below : Sdictionary-name> [ ckey>] i to access the value for key defined as “Karen” in above declared teachers dictionary, you will write “ >>> teachers [*karen*]_ 8rd Python will return Sociology } : “milarly, following statement > Brant Cxaren teaches", teachers('karen']) | Will give Output as ; aren teaches. Sociology counuter SCIENCE WITH PYTHON 84 ou access only rack ening jude square Awhile giving Ary tose aie mentioned Ee tre vale correspon TS fy square rackets B i the toons meets of he eons displays the entire 6 Consider following example: pot, "Vouel4” : "6", “Vowels” "arp svorel2" 2 (vowel "3s aordet sake coments of cia Note the Disp asi concent fro order a ura "vowel2! ‘vonel4 :'0', ‘Vowel? uf dictionary Prat nt er far rer of eerments ib >>» print (2) se, Vowel! :'3'} prin sees unaly sy ven d[*vowel2") the _— ee ost, tie ht en a AP i ae yop df'vouel4") eepenpunng ales string type. a “Asperabove examples, we con say that key order isnot guaranteed in Python This is becausein Python ditionsees, the elements (ey: tahte pars) are wionfered ; one cannot access elements per specific order. The only way to access a value is through key. Thus we can say that keys ct like indexes to access values from a di ‘Also, altempting to access a key that doesn’t exist causes an error. Consider the following sistent key (13) from dictionary d. onary statement that is trying to access a 10 yoo [23] NOMEN Traceback (most recent call last): Th fytos geen File “", Line 1, in clements (key : value pais) dkeyError : 13 unordered; one cannot a [13] elements 3 pt spate re The above error means that before we can access the value of a particular key using expression such as d[“13"], we must first ensure the key (13 here) exists in the dictionary. Like list elements, the | dictionary and values of a Followin x stored through their references. dictions 9.1 illustrates the same for a ‘ Boose" :3, “tern” :3, "hawk" : 1} Figure 9,1. References of keys and V4 are stored in a dictionary here are ae of tse in ment as coys act lowing 25 gs OCTIONARES qraversing © Dictionary edt tof a collectiox HP avers MIEOMS aecessin sans eon same and 824 proces se for 1OOP MAKES IE CDSS 10 ayers gntX SOF loop gor .keys() and toseeay mnlues in one go, you may write .values( ), as shown below (for the same dictionary | d created above) : >>> d.keys() dict_keys([ ‘Vowels’, ‘Vowel4’, 'Vowel3', 'Vowel2', ‘Vowel1']) >>> d.values() dict_values(('u. As you can sev that the keys() function retums all the keys defined in a dictionary in the formol a sequence and also the values() function returns all the values defined in that dictionary inthe form of a sequence. You can convert the sequence returned by keys( ) and values( ) functions by using list() as shown below : >> list(d.keys()) ['VowelS', "Vowel4", "Vowel3*, “Vowel2', ‘Vowel1' } >>> list(d.values( )) Tut, to" 'i', te', fat] A dictionary is a unordered set of key : value pairs. Ils values can contain references toan 7° of object. 2. Not a Sequence uae sting list and tuple, a dictionary is not a sequence because it is unordered ad ‘ments. The sequences are indexed by a range of ordi lence, ts." q 7 J , they are buta dictionary is an unordered collection. a! RUMErS. Hence, they 2% orm of inthe t() as wise, yr set of zero © og: DICTIONARIES pine OF Ro: No! Numb: 40 yiaionaries are indexed by i ‘eys. strings and numbers qpc2: Actor I fi fi le contains immutable oy; | poy But the values in ie iia | dictionary. ] Following dictionary diet has, poo dict1 = { y } >>> diet [0] ‘value for key | <—————— +f grape por dict1[(4, 5)] ‘value for a tuple-as-a-key >>> dict1[4, 5] ‘Value for a tuple-as-a-key poo dict1["3"] ‘Value for a string-as-a-key 4. Keys must be Unique Each of the keys within a diction dictionary, there cannot be However, tivo unique keys declared above : » Birdcoun = Notice that two different Keys SiMitoble: Like lists, dictionaries are 2° : ent Using the assignment statemt ‘[edictionary>[ conmutlh SCIENCE VATE PYTHON — 9 1 288 sod above : Forevample, conser the dictionary det del ye ora key a oy waged ine saa oe tiangee assigmiirer) stasemer seaieta["3"] « "changed tonew strs7” por diet21("3"] hanged to new string! ; ban toa dictionary using, 2 simple assignment stateren, 4 can even add a new heya Ifthe key already evists, then value is simply Jd be unique “But the key being added show das jement abov changed as in the assignment stat “>>> dtces[ned"] ="aneu pair ds aes” >>> dieta . (01 Value for key 8, 12: Value for key 1) (4 5 ipte-as-avhey, 3: Volue fora string-35-2 Mnew :'a new pair is added) Sy 6. Internally Stored os Mappings “Internally, the fey:value pairs of 2 dictionary internal function (called hash-function'). This way’ ): Value for a key’, ‘and for fur! : 7, are associated with one another with some of linking is called mappin; Keys Hash function Stored values koyt oye Valued | i Koy Key > / Figure 8.2 Internally Keys being mapped to Yalves 9.3. WORKING WITH DICTIONARIES Alter basics of dictionaries, let us discuss about various operations that you can perform o* dictionaries, such as adding cloments to dictionaries, updating and deleting elements dictionaries. This section is dedicated to the same. i! 9.3.1 Mulliple Ways of Creating Dictionaries You have leamt to create dictionaries by enclosing key:alue pair other ways of creating dictionaries too that we going fo discuss here. H “Hah function ian internal algorithm to map and link & Key with a stored vatues curly braces. There pICTIONARIES HON 9 Diclionary 1, method all the key:y, : alue pri ft sets jand enclosed in curly brane” © 1 ave already worked with thi © Written colle t Yorgpntssmethod, eg fatowing ta ‘ Testively, separated by ictionary Bee tionatis wate, snpleyee = Came: Soh eatery moloyce salsobeingccern aes ested + 10000, fed the same way : _ age : 2a tema paraiess vale Poirs 10 on Ematy Dict , Sen, GAN gis method, firstly an empy dic Heory Simply ne pair ata time. FEBonary is created and then k anid values are added to it __-@ Te create an emply dictionary, thore “(by giving dictionary contents in ‘Employees = {) Gi) by using dictionary constructor di w y oF diet() as show mutaeiien iet() as shown bolow : 9 Next step is to add key are two ways : empty curly 'PLy curly braces as shown below ‘alue pairs, one at a time as per [¢key>] = evalues synlax given below : some ) For example, in the adjoining statements we are first adding a |"Enployesl hey:value pair of ‘name's ‘John’, next statementsadds ane employee salary] = 1008 | eget i 10000 for Key “salary’ and the third and ast statement adds pe] = 24 ralue 24 for key ‘age’. This method of creating dictionaries is used lo create dictionaries dynamically, at runtime. 4. Creating @ Di {sing the diet() constructor of dictionary, you can also create anew dictionary initalize from specified set of keys and values. There are multiple ways to provide Keys and rales to dct) constructor. (0) Specify Key: Value pairs as keyword arguments 10 dicl() function, r the argument names are taken as keys of String type. nary from nome and value Pairs Keys as arguments and Values as their values. Here " 5 Pt ene Employee arene ="John’, salary = 10200, 28° = 24) cannon rm OF >>> Employee ames to ~ (‘salary : 10008, ‘age’? (i) Specify comma separated key vale P tenivd need to enclose them in cus braces 8 SHO" acs) ay ynet : ‘Johny salary #20200) 24, ‘name’ = “Jobe } sna. To give hey ste pa in this format, you pairs. ants of 359 Employee = dict ((™™ bo Employee --{salary’: 10000, "982? 2, john") ‘name’ COMPUTER SCIENCE WITH PYTHON, a arately. In this method, “ ding values separately. hey, k arately and correspon iments atinspecity eysuep parately in parentheses? and are given as arguments to the 2H) function, which is then given as argument of dict( ). - oe 7 Fint group contalns al ond Be tree im spe tcl (iene ‘ eee naa frrurient to ep funtion. The nit) function li phen | thet of corresponding key, eS | St anpument of dict) constructor ~ Jerre : >>> Employee = dtct( 2ipt Cnane’ ‘salary’, ‘age’), CJohrt, 18008, 24)) >>> Employee iD, J {salary : 1080, ‘age’ : 24, ‘nane’ : “John’} ‘The: ip func FECT with the first value of second set, se, = ‘ip function clubs first value from first set with the firs v (Second value fom, first set with the at value of second set, and so on, ¢g.,in above example, ‘name’ ig With ‘John, ‘salary’ with 10000 and ‘age’ with 24. Using these clubbed values, the dig) constructor method creates key: value pairs for the dictionary. » Uiv) Specify Key: Value pairs separately in form of sequences, tuple argument is passed to dict(). This argument (passed list or tu individual key: value pairs. That is, akey : value pairis In this method, one tq, ple) contains lststupleg Specified in the form of alist and there are as many lissasitemsof Outer list as there are key: value pairs in the dictionary. Consider the following example : See, there i one list ppe argument passed to dict )consiuctor, This st argument, it 1wm contains all keyvalue pain as late (5 list ype entries in one list here.) >>> Employee = dict({{"nand, “Joh, ['salory ', 10000), ['age, 247)) >>> Employee ay (salary : 10000, ‘age’ : 24, ‘nane! John’) You can also pass a tuple containing key : value pairs as list-clement or tuples as elements. Se following examples : The dict } meta is ‘contains Uist-etements | >>> Empl2= diet((['nane’, “John*], ['salary', 10000), [‘age', 24) ))/ | >» Empl2 {'salary : 10008, ‘age’ : 24, ‘name: ‘John’ } Provided tuple argument, The posed ile 8 of hey. values (5 lit entries in one ele The dict) method i proved tuple argument, The passed tuple comains uple-elemet of ey, sues (5 tuple entries in one tuple) >>> Empl3 = dict((Cnamd, obr), (salary, 16000), Cage, 24))) I >>> Emp13 : _ Csalary’ : 10000, ‘age’ : 24, ‘name’ : ‘Johr’} = >>> 2, ie, astuples. gig Elements to Dictionary, 2 add new elements (key ; 1 ‘you caf 8! nts (key value pain) , BUT the key being added mu) © 8 di an exists, then this statement aa St not exist ‘rare’, Using assignment as peta Med to dictionary. change the value of ling ep be tng. ene sy no egictdonary? [] = > Employee = (‘name : "John __ rn enployee(dept'] ='Sales' >>> Employee Newent added {'salary’ : 10082, ‘dept’ : ‘sales’, ' 1 "Salary : 10060, age: 24) AEE #24, ‘mane’: “Johny storing a dictionary inside another dictionary is called nesting Cf diine must know about nesting of dictionariesis that, you can erect eee dictionary. You cannot have a key of dictionary type ; you know the reason — only immutable types can form the keys of a dictionary, 9.2 A Dictionary contains details of ovo workers with their names as keys and other details in the form of dictionary as value. Write a program to print the workers* information in records format. | fon Employees = (John ; {age’: 25, ‘salary’ : 20000), Diya : Cage : 35, "salary : 5ee00)) for key in Employees : a ” Carefully notice, how the print ("Employee”, key, ernie Bot print (‘Age :', str ( Enployees[key]['age’] )) inner dictionaries, stores as vulues print (‘Salary :', str ( Employees[key][’salary] )) , Employee John + | Age: 25 Salary: 20000 | Employee Diya : | wget 35 \ Salary: 50000 933 Updating Existing Elements in a Diclionoy snows Tet you Updating an element is similar to what we did jus change value of an existing key using assignment as per following sy" dictionary>[] = >> Employee = (‘name : ‘John, 'sa1aY | 959 Employee['salary’] = 20000 | >>> Employee ys John} | {'salary - 2eeaq. ‘age’ 2 24, ‘name COMPUTER SCIENCE WITH PTHON «5 it in the dictionary as Inpietionaries the updation ang must ex But make sure that the key ce onsry. " stwciae new entzy will be added to the ate —_-nditlon of elements ae sy i othervvise new entry epeatue pairs you con eres In symtae. But for 383ton he Using this technique of adding bey 1g input (OM fey must OL AL Im the { ly at runtione By a6c:P! dictionary and for updation, the Key must exist the detionay, Zi —— i po! dictionaries interactive Following program illustrates this. ining names of competition winner student 8 Keys and 9.3 Write a program wo crecie a dietionary cont | ruber lr wis 0 ves n= dnt(Anput(’How many students ?“)) Comphinners = (} For a inrange(n) . ; key = Input("Hane of the student :°) value = int (input(*Munber of compet Conphlinners[key) = value Gh stitdons won :*)) print ("The dictionary now $5 2 print (Conphinners) - The sample run of above program is on fame of the student : Rohan i Nunber of competitions won t § .. i Name of the student 1 zeba | teeter of exeeritions to: 2 ane of the student : nihar umber of conpetitions wan : 3 ane of the student : Roshan Number of competitions won : 2 ty name of the student : James a urber of coapetitions won : 5 The dictionary now is : (Mihae £3, Rohar! = 5, Zeba': 3, Roshan! 2, anes! : 5) H How many students 75 3.4 Deleting Elements from © Dictionary : There are Ie» methods for deleting elements from a dictionary. Noy (9 To delete a dictionary element or a dictionary entry, ie, 3 heyoalue Pair, you can use del ‘“ command, The syntax for doing so is as given below C 9 : DICTIONARIES 293“ consider the following example : »>2 empl3 {’salary’ : 10882, ‘age’: 24, ‘name’ = ohn} ypvdel empl3['2ge') areenpl3 4 Sse, the dictionary now has {salary 10002, ‘name: “Johny fat enry remove put with del statement, the key that you are giving to delete must exist in the dictiona: otherwise Python raises exception (KeyError), if - = See below : _>>del emp]3(‘new] «——___ Trying to delete a non-existent key raceback (most recent cali last): File "cpyshell#22>", line, in «nodules del emp13[‘new) | KeyError : ‘new (i) Another method to delete elements from a dictionary is by using pop( ) method as per _ following syntax : .pop() | Thepopt ) method will not only delete the key:value pair for mentioned key but also return the corresponding value. Consider following code example >> employee _ fisalary’: 10000, ‘age’ : 24, ‘name! + ‘John’ 99> employee. pop(‘age') 26 ae show here forthe erent dea >>> employee Element delete from dictionary {salary : 10000, ‘name’ : 'John'} aa I you try to delete a key which does not exist, the Python returns error. See below : >>> employee .pop('new) Traceback (most recent call last): File “", Line 1, in employee. pop("new) KeyError : ‘new . However, pop() method allows you to specify what to display when ra given ey does not Okist mates teen the default error message. This can be done as per following syntax : edictionary>.pop(, «in-case-ef-error-show=ne7) For example : >>> emplayee.pop(‘new, "Not Found?) t Found: message. See, nove Python returned the specified message in Place Of exronmeseag COMPUTER SCIENCE WITH PYTHON ~ 3 “294 9.3.5 Checking for Existence of @ Key seth dictionaries as wel But they can ch paren orsoniyTo check for whether value is present ‘eased on reverse leapt nea este a aie Proper ‘rode for that. (Solved Pr ‘oblem ay vie nei To Se eenbeithip operator for a Key's presence in a dictionary, YO tas per syntax given below ! ckey> An key? not dn ¢dictionary> — The in operator will retum = The not in operator will re otherwise False, the dictionary, otherwise False vyis present in ot present in the dictionary, Trueif the given ke; i turn Truc if the given key 1s ni Consider the following examples = >o>enpl » (salary : 10008, ‘age : 24, __>>7age! An empl True >>>"John' in emp] False ‘name’ : ‘John'} ZA pr done not in eepl Yohn' is not a key, hence Python rewurned False, as in only ~ heck in heya of the detioray. >2>‘age' not in emp] False Please remember that the operators in and not in do not apply on values of a dictionary, if youuse them with dictionary name directly. That is, if you search for something with in or not in operator witha dictionary, it willonly look forin the keysof the dictionary and not values, >>> dict1 {‘age’: 25, ‘name’: 'xyz', ‘salary’: 23458.5) , , The In and not In operator check >>'name in dict fee winrned Fab Uf you bid for membership only In eys of True a search for a value in a dictionary using the dictionary and notin values. Sa pootxyz" indict2 False However, if younced tosearch for a value in a dictionary, th i ; then y i th ‘edictionary. name>.valuest ), ic, ry, then you can use the in operator W! >>>"xyz! in dict. values() True a ding ecictionary> ve Fats eaten value(s can ook ' 9.3.6 Preity Printing @ Dictionary You generally use print function to print a dictionai | i 7 7 ry in Python, eg, if iti as Winners = Rohan’ :5, ‘Zeba’: 3, ‘Roshan’: 1, 4 8 if you have a dictionary | print it, Python will give result as : shan’: 1, ‘James’: 5) and if you give a print() 1° >>> print (Winners) a in ada wey of prt {‘Nihar': 3, 'Rohan': 5, ‘Zeba': 3, ‘Rosha sae ei detec nO 2 "James": 5} 1cronaats 25 a i pove aye of ater can still make out the keys and values, but i te se le ed presentable ? \y way of printing dictionary in a way that mal there certainly is a way. For this, you need to import json module by giving statement wot json (recall that in a program the import statement should be given at the top.) pps en OU can use the function dumps()) of json module as per following syntax inside print( )+ son.duros(, indent» >» print(json.dunps (Winners, indent = 2)) { swihar" : 3, Dictionary name srohan"? 5, *zeba": 3, —.. * Keyvolue pairs in separate lines and 2 space in front of every Roshan {ine because you gave value 2 for indent (Indent = 2) syanes": 5 } 937 Counting Frequency of Elements in a list using Dictionary Since a dictionary uses key-value pairs to store its elements, you can use this feature effectively if you trying to calculate frequency of elements in sequence such as lists. You can do this as: © Create an empty dictionary # Take up an element from the list List (first element 1st time, second element 2nd time and so on) © Check if this clement exists as a key in the dictionary : Ifnot then add {key:value} to dictionary in the form { List-element : count of List-element in List} Following program illustrates this, But before we move on to the program code, it will be good if we talk about an interesting and useful function split() that you can use with text to split it in words, (it will come handy especially if try to find frequency of words in a sentence or in a text file). The split() works on string type data and breaks up a string into words and creates a list out of it, e.g., >>> text = "This is sample string” >>> text = “one, two, three” >> words = text. split() >>> words = text.split(", ") >>> words >>> words Uthis', '4s', ‘sample’, "string" Cone’, "two", ‘three’} a si AS SESS STF RT OTE {tus pes ata ods he eof never (), There ered Is namely were By default split() breaks up a text based on white spaces, but you can give a separator character €8,, see sample code on the right above. Now consider the following program. a COMPUTER SCIENCE WITH PYTHON ~ yy 296 9.4 Program to count the frequency ofa list-lements using 2 dictionsny P : | counting frequencies in list ym import json ['this', "is', ‘ay ‘super’, sentence = "This is a super idea This \ idea’, "This', ‘idea’, ‘wit}', idea will change the idea of learning” | tenange’. ‘the’, ‘idea, words = sentence. split() (soft, *Tearning’] \ 80 nett ( | for one inwords: eye ‘ key sone AL (hey scountof hey) if key not ind: tw dictionary j count sverdsccint(key)—_/ [key] = count | | print("Counting frequencies in list \n", words) print (json.dunps(d, indent = 2)) The output produced by above code is shown on the right a 9.4 DICTIONARY FUNCTIONS AND METHODS Let us now talk about various built-in functions and methods provided by Python to manipulate Python dictionaries @ len{ ) method This method returns length of the dictionary, Le, the count of elements: (key:tulie pairs) in the dictionary. The sya to use this method is given below : : Jen() = Teles dictionary mam Example : argument and returns an integer 2»employee « (iasu : “Joh, “salary : 10000, ‘age’: 24) 222 1en(erployee) 3 —_ ji The lent } returns the evant of Aeystalae pn fom the sateray __ Pemployee|"dept’)} «Sales! >>>len (employee) 4 a Se oher alding a new entry the _2he clear{ ) method ‘eft cred This me | Abis method removes all items from the dictionary and the dictionary becomes empty diction? Post this method. The 16a Th 1d is given below : ‘Blethonary-etear(y ~ Takes no argument . returns no palue Bice $s _ DICTIONARIES, ow ple: Lait Employee = (‘name ohn’. » >» Employee. clean() “5m Employee a € See. now the Alctionary emp The clear method does not de dictionary, x If, however, you want to delete the dictions JUSt delet. abject remains, then yoy Onary i ary iil 1 can use del slateme, alone For example : rents inside the © the dictionary, tionary is also r iti >>> Employee = removed and no ionary name (name: ‘394 lary : 199 [Siti 99> del Emplo ee . caemplivec ill dtee The ea) removes at the elements of a dictionary and makes. Traceback (most recent ca) last); sos Fille ">> empl {salary : 10898, ‘dept’ >>> enpli.get (‘dept’) | ‘Sales: key if key exists in the dictionary. If you only specify the ei ed value for gi en key if key exis ' a an ion does net exist in the dictionary, then Python will return error >>> empl get desig’) / Traceback (most recent call last) ae File "", line 1, in empl1. get (‘desig’) Jotined Nametrror: name ‘desig’ isnot ‘Sales’, ‘age’: 24, ‘name’ : ‘John’ te error message as sccond argument ; ‘ also specify your own custom " place of error, you can | >>? empl1.get(‘desig’, "Not yet") reer yet! ot found") >>> empl .get(‘desig,, "Error! ! Key n “Error! Key not found COMPUTER SCIENCE WITH PYTHON ~ xy “items{ ) method ic of (key, value) tuples. Not | Fu: method returns alo th tes nthe dtr sa evens kkey, ples. Note that these are returned in no particular order. items() - ; ~ Takes no argument ; Returns a sequence of (key, value) pairs Example : The adjacent code gives output as; e employee = {'nane! : "Johni, ‘salary’: 10000, ‘age’ : 24} (‘satary', 10000) i myList = employee.items() Cage’, 24) for x inmylist : ( tnane', "John! ) print (x) As the items( ) function retuns a sequence of (key value) pairs, you can write a loop having two variables to access key value pairs, ¢,., The adjacent code gives outputas: i enpl = {‘age': 25, ‘name: ‘shuvan', ‘salary’: 20000} | age } seq enpl.itens() thuvan name for ky, v1 in seq: 20000 salary print(val, key) This loop has two iteration variables ky, vl because the function items() returns a list of tuples and ky, vl is a tuple assignment that successively iterates through each of the key-value pairs in the dictionary ie, each key-value pair is assigned to loop variables ky and vl at a time. 5, The keys( ) method You have already worked with this method. This method returns all of the keys in the dictionary as a sequence of keys (in form of a list). Note that these are returned in no particular order. “.keys() anita = Takes no argument ; Returns a list sequence of keys Example : >>> employee {'salary : 10000, ‘dept’: ‘Sales, ‘age’ : 24, ‘name’ :‘John'} >>> enployee.keys() [salary, ‘dept’, ‘age’, ‘name'] - The values( ) method ‘This method retums all the values from the dictionary as a sequence (a list), Note that these are Teturned in no particular order, The syntax to use this method is given below : .values() ~ Takes no argument ; Returns a list sequence of values Example : >>> employee {salary : 10000, ‘dept’ : ‘Sales’, ‘age’ : 24, ‘name’: ‘John'} fo» employee. values() [10208, ‘sale: 24, "John’} y ‘ DICTIONARIES oot ypdatel ) method 2 ‘ey: 5 1, js method merges Key : value pairs from the new dictionary into the original dictionary, adding acing as needed. The items in the new ai i ales "realy there with the som oe cteonary are added tothe old one and override qhe syntax to use this method is given below : pre 7 This dictionary’sierts will be takert we , update ( >? employeel = {iname' : “Iohn’, ‘salary : 1¢280, ‘age’ : 24) ements of dictionary >>> employee? = {‘nane’ : ‘Diya’ i i set ave overridden the Ployee2 = {'nane’ : ‘Diya’ , ‘salary : 54008, ‘dept’ : ‘Sales'} a of dictionary — >>> employeel update (employee2) feager! having the sate heys >>> employee vifos ‘nae’ ard “salary” {salary : 54920, ‘dept’ : ‘sales’, ‘nae’: ‘Diya’, ‘age’: 24} >>> employee2 {salary : 54000, ‘dept! : ‘Sales’, ‘name’ : ‘Diya'} 1. Why are dictionaries called mutable types ? | 2 What are different ways of creating dictionaries ? | 3. What values can we have in a | dictionary 2 | 4 How are individual elements of dictionaries accessed ? 5. How is indexing of a dictionary ferent from that of a list or 2 string ? §& Which of the following types qualify to be the keys of a dictionary ? (6) String (b) tuple (c) Integer (@) float (e) list (f) dictionary 7% Can you change an element of 2 Yequence or collection ? What if the collection is a dictionary ? What if the Hequence is a string ? S Wat do you understand by ordered Collection and unordered collection ? 4, int examples a eaisting dictionary ? & Alctionary and if so, how ? How do you add key:value pairs to #7) ‘This method is equivalent to the following Python statement: for key innewDict.keys() snewOict 1s employee2 here dictionary[k]=newict[k] DICTIONARY HANDLING = ) AND |ANIPULATION (peAnrUATiON Progress In Python 9.41 Sei This PrP session aims at strengthening skills related to Dictionary handling and manipulation. pep dece vi ve have come to the end of our chapter. Let us With ss wt we have learnt s0 far. quickly revise w Gan you remove key: value pairs from & COMPUTER SCIENCE WITH PYTHON _ 300 ler Us REVISE / Jemenes inthe form of a keyvatue pair thet associate Keys 10 values, Dictionaries ore mutable with el 4 The hays of a dictionary must be of iminitable (yPes- iat 1r moppings oF hashes. %1 Dictionories are also called associative arrays oF mo — “dmenetn, In Python dictionaries, the elements (hey: value pairs) are unordered ; one Cr inot access Per speclficondey, through {) and through dici() constructor, jictionories c ted in multiple ways — : snares ain et ot ita in syntax. But for addition, the hey must noc exig In Dictionaries, the updation and addition of elements are si in the dictionory and for updation, the key must exist tn the dictionary. hal . er e pop( ) method. % To delete an clement, you con cither use del statement or use pop Some useful dictionary methods and functions are : fen(), ctear(), ge). Krems(), keys), values() and updarep, ih dictionary % 4 Keys of a dictionary must be unique. % & ork % % The membership operaiors in and wot in only — The clear( ) function removes all the items from ictivnary but the dictionary ubject exists as an empty dictionary. % The del statement removes a dictionary object atong with is items. After this, there exists no dictionary object Solved Problems (er A cs 1. How are dictionaries different from lists ? Solution. The dictionary is similar to lists in the sense that iL is also a collection of data-itemsjust like lists BUT itis different from lists in the sense that lists are ‘Sequeutial collections (ordered) and dictionaries are non-sequential collections (unordered). Inlists, where there is an order associated with the data-items because they act as storage units for other objects or variables you've created. Dictionaries are different from lists and tuples because the group of objects they hold aren't in any particular order, but rather each object has its own unique name, commonly known as a key. 2. How are objects stored in lists anc dictionaries different ? Solution. The obje or values stored ina dictionary can basically be anything (even thenothing, type defined as None), but keys can only be immutable type-objects. eg., strings, tuples integers, etc. ° 3. Wher are dictionaries more useful than lists ? Solution. Dictionaries ean be much more useful than lists, For exemple, suppose we wanted © Store all our friends’ cell-phone numbers. We could create a list of pairs, (name of friend, phone ‘number), but once this list becomes long enough searching this list for a specific phone numbst Will get tite-consuming. Better would be if we could index thelist by our friend's name. Ts Precisely what a dictionary does. Gar sequence operations such as slicing and concatenation be applied to dictionaries ? Why ? io Solution. Noy Sequence operations like slicing and concatenation cannot be appl, sctionaries. The treason being, a dictionary is not a sequence. Because it is not maintal j Any specific order, operations that depend on a specific order cannot be used. coupler 9: DICTIONARIES Why can't Lists erm be used as keys ? 5 Solution. Lists cannot be used as key’ i ol ts eys in a dicti ‘Jictionary can have only keys of imimutseae? because they are mutable, And a Python ¢ types. Ifthe auditio rw key:valie &_ Ifthe audition of mew key-value pair causes the size of the dictionary to grow beyond is original » keyoud ils original size, an error occurs. True or false ? Solution, False. There cannot occur an . an ertor because Dicti . Soli gow or shrink on and as-needed! basis -ause Dictionaries being the mutable types, they Consider the following code fragments. What outputs will they produce ? () aDict = {"Bhavna':1, “Richard":2, “Firoza™:1@, “Arshnoor”: temp =@ ° 128, nor” :20) for value in aDict.values() : temp = temptvalue print(temp) (i) adit = { "Bhayna":1, “Richard":2, “Firaza":20, "arshnoor™:28} tenp =" " for key in aDict: if temp ¢ key print(temp) *zeshnoor™:20) (ii) avict = { 'Bhovna’:2, "Richard™:2, "Firora"s20y k= “Bhavne ve-l 4 k in aDict: abiet[k] print(aDict) Solution. 33 (i) Richard — 1, 'Richard’ :2, ‘Firoza’ = 10% *arshnoor’ 20} ny soork seith Keys of @ dictionary ut le check for the presence of a value in a (if) { "Bhavna" 8, The membership operators dictionary, you need to write jane that print the correspon acoule. part of given dictionary or secks whether the given value es print an error mess Write a Python prose fakes a value and ¢ i ding key otleerevise nol, If itis, it should Solution. dicta = (0 :"Zero", 2 3 :*Three", 4 s*Four", 5 :°FAve") ans = "y" while ans =* ‘y' on ans == 'Y": val = input (“enter value print(*value", val, end © for kin dict : if dicta[k]== val: print ("exists at”) 2 :*TWo"s k) else: print(*net found”) ane = input ("want to eneck more values? (yin) =") COMPUTER SCIENCE WITH FrMHON _ 302 yea ond “Zt tree sb a EIST leg, hyn” or 19, Marks of theee students “Sun! itionarssreepetiely +70, 3178) a (24,2570, 3¢ Parte 270, 2188, 3! areeme herr deta along th tet asad hen rit hut g a ores the marks det Cratea ested dictionary that shown below : | Hane | yma j Subject (key) Marks (value) : 40 3 80 3 ee ane Zeba Subject (key) Marks (value) a 70 2 80 GI 3 90 tose & Sunitd Subject(key) _Marks(value) Me 1 40 he 2 7 ii 3 70 Solution, OL (2:40, 25 70,3: 70) Ns a0 62) : om B= (2 $0, 3: 99) del i, *Ryna” : d2, "Zeta" : d3} Typ for x in ds.keys() + print (" ] print (x) : print (* Subject(key)", '\t, "Marks(value)*) 3 for y in eax}. keys() : print (°°, y,\t\t, dapxdty]) 4 print() : 10. Consider a dictionary my_points with single-leterheys, cach followed by a 2-element tuple representing ‘ coordinates ofa point ins an x-y coordinate plane, my_points = { tat (4, 3), 'B' : (1,2), "et 5 (5, a) ) ’ Writea program to prin the maxirtwm value from within al of he values tuples a see inde ' For example, maxinnn for 0% index will be comy puted from values, and, ie. all the entries at tk indexi* the valne-tupte. JONARES 303 + on “ha, om? ts, ri theres in flloncing format: raxinun Value at index(ey_petmts, e) = § raxinun Value at index(eypetnts, 4) 23 setution mypoints = ("as (4, 3),'¥: (1, 2), ! Pring highest = (8, 6] , hen inte = 0 for » in range(2) : init «8 for b tn ey_potnts.keys(): val = ay. points[b) {a} IF inte oe 82 highest{a) = val inte se a Af val > highest[a) = highest (a] = val print ("Maximus Value at index(ay_points, *, a" 5.1) } GLOSSARY 2 ae ‘Amuse, unordered collection wth elements inthe form of @ key-value pai thet extotate keys to velue. | atonery | mopping inking of @ her wth © value rough sme intemal neton (hath arto. Mestng Having on element of similar type inside enother element leotip ——_-Adictonary opertion that fates Ley and finds tha corresponding volve. Assignments Type A: Short Answer Questions/Conceptual Questions Jered collection of objects 7 dictionaries ? ‘cannot always be used as keys in a dictionary. What is the 1. Why is a dictionary termed as an unord) 2. What ype of objects can be used! as Keys int 3. Though tuples are immutable type, ye! they condition to use tuples as a hey in a dictionary ? "y store in: (e) ictionary-values 2 (b) dictionary-keys ? What all types of values can yor is contents, it, can you sort the contents of a dictionary 7 CCan you change the order of dictionary Inno more than ane sentence, explain the following Python error and how it could arise: Typetrrer: uohashable type: '14st" Can you cheek fora vale inside a deionay wi 8 dictionary using in operator ? & Dictionary is a mutable type, which means you cay modify its contents ? What all is modifiable in a dictionary ? Can you modify the keys of 2 dictionary ? 9. How is det 1 and det D[ehey>] different from one another if D isa dictionary 7 ow is clear) function different from del edit statement? gin operator? How will you check for a value inside 10s Understa nding Sorting Fg soa Introduction What is Sorting 7 ‘a INTRODUCTION In general terms, as you see in many junior level activities, sorting means — from a pile of Miced objects, picking and placing identical objects into separate groups. But in computer tems, sorting has different meaning. Computers often deal with sequences having multiple tlements, Sorting in computer terms means arranging these ¢ ‘ments ina specific order cs increasing order or decreasing order. In this chapter, we shall discuss what sorting means in ‘computer terms and two techniques of doing it — bubble sort and insertion sort. COMPUTER SCIENCE WITH PYTHON . t 10.2 WHAT IS SORTING ? arranging elements in 2 spel oe oe decenaing é song oi noose HY mo jncreasing order of descen ta ™ AWE ZED ee Sorin, ik compel te 3 ding order will be: {efecs to arranging eleme the sored sequen in aces specie order cee 5 [12,4 5,6, 8) descending a and in decreasing order, it would be: fig ea boi : y rectly in your day to day life, ¢g, if yoy ‘sorting ues’ unknowingly, indirectly 9 day te eg You have used oe of containers with different sizes, what do you do? v0 Pu 7 Bae aan ee en emaler than it into it, further smaller Into it an ; container fi ‘Smallest container in the last. This is sorting only. (sce below) vl uu? Uw 4 Similarly, when you arrange your books in the order of their thickness, it is also sorting, There are mulliple ways or techniques or algorithms that you can apply to sort a group of iutibte sort, heap’ sort, quick sort etc. Repeat orl ele In this chapter, we shall talk about two sorting algorithms ~ bubble sort andl insertion sort, 10.3 BUBBLE SORT The basic idea of bubble sortis to compare two adjoining values and exchange them if they are notin proper order. To understand this, have a look al figure 10.1 (on next page) that visually explains the process of bute sort For instanee, in following, figure (Fig. 10.1) unsorted array is being sorted in ascending order using bubble sort. In every pass, the hea its appropriate position in the bottom Renault iest element settles as Algorithm —8u28te SoRT IN Linear List Races 2. Fort=L TOU 2 ForJ=LT0[ (u-1)- 1] # need not consider alread A that ds why (u—1)—1, 3. Af AR[J] > AR[D +2] then + swap the values ly settled heavy elements “ tenp = AR] 5 AR[I) = AR[I +1) 6 AR(I +1] = temp #endof if : end of inner loop 7. EW, # end oF outer 1oop geet 10° UNDERSTANDING SORTING 305 Two adjacent elements being compared are shown in shaded boxes. m ro Fg Fg |S pep ewe Felt oe tele be Gey Be : 3 [9 19 Ta] ys22 f i i 4t2 f [2] v7? Pr a7] 7 spy Lr ial 7 [Baltes [a ‘ il mess ! 4 aie poe ‘Again repeating the 2amo process (heaviest a) a3: fomep 5 5 = 3 3 5 13 (he) 3 a 7 7 3 ww [erence ays > a t: ie 2 ec a az iy a W Wir 19 ewan z 4 £ 4 ely as # # 8 = [22] (Secone L28 heaviest s 5 s] comes | 331 | sway 2 2 ares [21 wap A spprepeate| =| ik aie TV 4ro change = S|, “Desson) [13 ! air 2 fa7]y Tt swap 24 els 4 4 aly ow 9 3 1 19 (os 181 a 28 28 28 heawest) [2e rt 2 swap 5 + t : a az] $I ST a = ig Hi aye? ss tr a7 | W 7 MW 19 | 19 19 20] 2 22] (nextheaviesty [2s a frocrance 2), 2 5 [ot femap 4 3 4 [=] ity is 3 = fr 7 hi? | 9 19 19 2 Ea [zs] Figure 10.1 Bubble sort. Wecan now write code for bubble sort as shown in algorithm on previous page. Notice we have Kept in mind that since one heavy element settles at its right position in one complete iteration, Next time, we need not compare that element. That is, after first complete iteration, we can have 1)ess number of comparisons in next iteration (as 1 heaviest clement has settled in the end) ; alter second complete iteration, we can have 2 less number of comparisons in next iteration (as 2 heavy elements have setiled in their correct position by now) and so on. Following Program shows Python code for the same, the bubble sort technique. ‘ COMPUTER SCIENCE wire, Pn, 30 " | 10.1 Program to sort a list using Bubble sor. alist «[ 15, 6, 13, 22, 3, 52,2] 4 —— We have taken a pre-iniiaticed ty (8M input a Tt prior yo nye You asaem print (“Original list 4s :*, alist) com ere tar 9 Tt peor t0 sorting ip n= len(alist) # Traverse through all List elenents for 4 inrange(n) : * Last i elements are already in place This expression will ensure that we for J in range(o, n-1-1): compare the heavier ee Rtraverse the list from@ ton-4-1 Thea sete at corer postin, # Swap 4¢ the element Found 4s greater # than the next element if aList[J} > alist{j+4] : aList(J], alist[J +1] = alist[j+1], alist[j] Print (“List after sorting :", alist) The output produced by above code is like. | originat ist is = OS, 6, 13, 22, 3, 52, 27 F | List after sorting : (2, 3, 6, 13, 15, 22, 82] Coleuloting Number of Operations Let us now consider number of operai Operations is an important aspect to know CPU time. Two programs with different logic can deliv will accomplish the {ask in lesser number of operations. | Tocalculate number of operations taking place tions taking place in above Program. Number of W as more number of operation. S Means more usage gf the same output but the efficienteny in above program, let us keep the things simple: 1 operation per statement that will include assignment, comparison and steap may take more than 1 operation to ering it as 1 operation for simplicity sake and underst Now consider this first : © Weil conside comparison swap ee [Please note Perform but we ar ‘anding sake] Wa. of Operation salist = (35, 6, 13, 22, 3, 52, 2] + print ( “Original list 4s = len(atist) alist) for 4 4n range(n) : F Last 4 elements are already in Place so aga for 4 tn range, nt-2) & | teauisesy > stssetsnay ; + conparsoree —] [ MASH), aLGstLJet] « aLtst( goa), alist(y] X<__tawapon___ } BrInt List after sorting: ') alist) yr peow 10: UNDERSTANDING SORTING ff $0 otal number of operations taking place in above code can be calculated as: Operations in Line 1+ Line 2+Line3 Ee =3 operations + Operations in Lines 4.7 (for loo a3 Eg) + Operation in Line 8 P) (Vo be calculated) Eq = 1 operation Let us calculate operations in Outer for loop : Outer for loop repeats m times [for n as 7, it is repeating 7 times} So total number of operations in outer loop, for loop are : Operations in Line 4.7 x7 times =Line 4=1 op = Line 5.7 = Inner for Loop Inner for loop is repeated (it~ i—1) times (s0 6 times first time, 5 tirmes second time, 4 times third tinte and so on) = Line 5=1o0p +Line 6 =1 op | + Line 7=1 op =3 ops Inner for loop performs 3 operations in single iteration | | So outer for loop operations are : | Ist iteration (= 0) | =1 op (Line 4) +3 ops (Line 5-7) x 6 times =19 ops inner for loop: 2nd iteration f= 1) =1 op (Line 4) +3 ops (Lines 5-7) x 5 times = 16 ops 3rd iteration (7 =2) = 1 op +3 ops x 4 times = 13 ops Ath iteration (7 =3) =1 op + 3 opsx 3 times = 10 ops Sth iteration (7 =4) = 1 op +3 ops x 2 times =7 ops 6th iteration (7 =5) =1 op +3 ops 1 times = 4 ops 7th iteration =1op+3x0 times =1o0p Total ops in outer for loop = 70 ops i So putting this value in reference eqn. (1) given above 4 ops Total operations =3 ops +70 ops +1 op One above given Bubble sort program takes approximately 74 operations when n is 7 for n=8 it will be about = 96 ops for m=9 it will be about = 121 ops | for n=6 it will be about = 55 ops forn=5 it will be about = 39 ops COMPUTER SCIENCE WITH Pry, a So with larger values of 1 it increases. - Calculating number of operations this way will be cumbersome. Let us concentrate On cru operations taking place — Comparisons jd Suappings as these are major operations taking pj,. Total number of comparisons in bu [evens @v—2)40N-9+(N-D HD) om ble sort is ee (2)+0)=NN-1)/2ie, zn? Let us see how we have reached at this number : a ‘The outer Loop iterates once for each clement inthe given sequence Se N times, where N isthe number of elements in the given sequence. The inner loop iterates N ~1 times for first iteration of outer loop, N-2 times for second iteration of outer loop, N ~ 3times for third iteration of outer loop and this process continues, For the first iteration of the outer loop, when we are trying tO place the largest elementig] its correct position , N'~ 1 comparisons takes place {the first comparison is made between; the frst and second elements, the second comparison is made between the second and thing) elements, and so on until the (N - 1)" comparison is made between the (N—1)" and the N" clement.] | © For the second iteration of the outer loop, there is no need to compare against the last ‘element of the list, because it was put in the correct position on the previous pass, Therefore, the second iteration requires only N - 2 comparisons. ! © Similarly the third iteration requires (N - 3) comparisons, and so on. | Thus, Pass Comparisons 1 N-1 2 N-2 3 N-3 N-l 1 This gives us total number of comparisons as : (N=1)+(N =2) + (N=3) + (N =A) + ON — De) (I) =N(N = 1) /2= NF The number of swapping will vary depending upon th ments of the sequence : © In the best case, ie, when all the clements of the sequence are already sorted (fey i8 desired sort order), no swapping will take place. =n comparisons +0 swappings = N? ops ° Havre. in the bilo ie, when al elements are in opposite order, every comparisee ingen *N 2 comparions +N? swappings = 2N? ops we determine i y i kt crf otters es me program than programs with higher epee seein coud me SO | 110: UNDERSTANDING SORTING owe Now that we have talked about . algorithms, let us quickly recap hove bane oF operations and efficiency of a bubble sort Look at the figure below that shows the wor every pass and changes after eve pass are shown with colour, king of Bubble sort, ie, it shows the array alter TY Swap takes place. The elements being compared in every f original 14st ts: (15. 6, 13, 22, 3, 52, 2) weeetteration 1 of outer Toop r ateratids 4d of = jon 4 of outer Toop — ust after pass 1: (6, 25, 13, 22, 3, 52, 2) Use after pass 1: (3, 6, 13, 2, 15, 22, 52) \ bus after pass 2: (6, 13, 25, 22, 3, 52, 2) List after pass 2: (3, 6, 13, 2, 15, 22. $2] | Uist after pass 3 (6, 13, 15, 22 32,2) List after pass [3, 6, 2, 23, 15, 22, 52) Ust after pass 4: (6, 13, 18, 3,°22, 52, 2] List after pass 5: (6, 13, 18, 3, 22, 521 2] —Iteration 5 of outer Toop —- List after pass 6: [6. 13, 15, 3, 22, 2, $2] List after pass 1: (2, 6 2, 23, 15, 22, 52] List after pass 2: (3, 2, 6, 13, 15, 224 52) —tteration 2 of outer loop —- List after pass 1: (6, 13, 15, 3, 22, 2, $27 Ust after pass 2. (6, 13, 15, 3, 22, 2, 52) Ust after pass 3: £6, 13, 3, 25, 22,2, 52)” bist after pass List after pass 4: (6, 13, 3, 25, 22, 2, 52) List after pass Sz (6, 13, 3, 15, 2, 22, 52] —tteration 6 of outer Toop — 2 (2, 3, 6, 13, 25, 22, $2) —tteration 3 of outer loop —- List after pass 1; (5, 23, 3, 15, 2, 22, 52] List after pass 2: (6, 3, 13, 25, 2, 22, 52] List after pass 3: (6, 3, 23, 15, 2, 22, $2) Ust after pass 4: (6, 3, 13, 2, 15, 22, 52] WA) current element CE 155 | 183 torn by {poston and ban pu co ‘element ( 11) at Hs correct postion [ss] oq G3] La ayaa] 14.25] 185] IFS erat tonone> ori [i163] Done. Sorted} to ght oy 1 positon and then pa ct lament (13.4) a ts correct POR” 10: UNDERSTANDING SORTING docode for sortin, eps orting a Sequence A using inserti ——— yasgiven below. Notice that loop is started from nd ‘clement qawards (ie., index 1 onwards) because left to it is single element sub-list and a single clement list is always sorted. (Insertion sort passes: through |ford=1ton ' y : 3 key=A(i], J=ina 3] | whdde(j > 6) and (Af) > key)do 3) | A(j +1) =ACj) 3 jeje. ° AJ +1] = key python code for the same will be as listed in following program : alist = [15, 6, 13, 22, 3, 52, 2] op == print (“Original list is :", alist) for 1 in range(1, len(aList)) : key = alist(1) jei-a while j >= @ and key < aList[4] : aList[j+1]=aList[j] #shift elenents to right to make room for key je3-2 else: aList[j +1) = key print (“List after sorting :*, alist) p 10,2 Program to sort a sequence using insertion sort Output produced by above program is as shown below : |) original Vist is : (15, 6, 13, 22, 3, 52, 2) | Uist after sorting : (2, 3, 6, 13, 25, 22, 52] Number of Operations ‘As we mentioned during bubble sort discussion that two costly operations are comparisons and swapping/exchanges. Let us concentrate on these two costly operations while considering number of operations in insertion sort. Look at insertion sort code given below with highlighted comparison and exchange operations. for 4 in range(1, len(aList)) = j key = alist[i] jei-2 while j>=@ and key parteese us REVISE LeT t 2 & ‘sorting of on array means arrongi ed and exchanged if Hey are ROE ues are compa? eq. In bubble sort, the adjoining ¥e % ing the array elements ino specified order. repeated until the entre orray is sorted. ied otan oven son each scesivciement picked Ise Ived Problems ; order using (i) Bubble Sort (ii) Insertion Sort, 89, 20, 31, 56, 20. Sort this array’ in ascend 89, 20, 31, 56, 20 Given an array Solution, Given array is (i) Bubble Sort " I 89, 20, 31, 56, 20 i 1126, 89, 31, 56, 20 TI 28,31, 89, 56, 20 (Bold elamenis sapit m1 IV 28, 31, 56, 89, 20 tat thay are 1 v 31, compa a v 20, 31, 56, 20, 69 eas) I 31, 56, 20, 89 VIT 28, 31, 56, 20, 89 VIII 26, 31, 20, 56, 89 IX 28, 31, 20, 56, 89 X 28, 31, 28, 56, 69 XI 28, 20, 31, 56, 89 (As you can see that Bubble Sort is taking up more number of operations (as more iterations) 89, 20, 20, 20, 20, than insertion sort to sort this same array (a very small array, though) Given the following steps to sort an array, which sort is this ? 62 4 4 4 4 Solution. Bubble sort. Which of the following sorting methods will be the best ficienty, considering the fact that the sequence size is (A) Bubble sort Solution. For smaller sized compared to bubble sort. not very large ? (B) Insertion sort You are asked to sort 15 randomly generated numbers. (A) Bubble sort You should prefer i (B) Insertion sort Solution. Insertion sort is a better choice for Small sized seq juences, {ii) Insertion Sort 20, 31, 89, 31, 31, 89, 31, 56, 20, 31, 56, 56, 56, 89, 56, COMPUTER SCIENCE WITH PYTHON In proper order. This process 5 cppropeiate postion Inthe previcusly sorted erry, if number of swappings done, is the only measure f Sequences, there are lesser number of swappings in insertion sort 85 319: RSTANDING SORTING 1p: noe intenance work, i tof the miairl i YoU are entrusted wit £ an order, at the end of cach day. The ideal choice ine Ofrearvanging the library books in ashlfIn (a) Bubble sort ©) Insertion vo cowtion Insertion sort castle the follow Ist: 132, 33, 5, 2, 14, 4, 22, 39, 34, op ‘ ing is av , she following is a view ofa sort gn 1m Progress (after a few passes) ofthe above list. Identify the sorting oritha sed 2 1, 5, 14, 22, 32, 33, 34, ola }, 34, 39] 1-944, , “A, 2, 5, 14, 33, 22, 39, 34, solution: (2) Bubble Sort —(b) Insertion sort _—_ Oe atrill tite following list Look like oe ;, Wate ef ater 3 passes of insertion sor algorthom ? Show thelist after every pass. = 7 n 15 10 gelution. Elements being compared are shown in black shaded cells. First pass 16 ay u 15 10 No swapping - 16 1g u 15 10 Second Pass A 16 19 l nn 15 10 16 19 | i 15 10 ic a ee i 16 9 15 10 Third Pass iW 16 WW 5 10 n 16 vy 15 10 | SS u 15 16 » |. © Itong a !nwkich situation, would you prefer bubble sort over insertion sort ? Sltion, Bubble sort would be ideal sorting technique for situations where data can be read only i, Uentially (¢ , data stored on magnetic tapes). As bubble sortalso compares two adjacent records, be suitable (or such a situation. But, nowadays, such a situation is rare.

Potrebbero piacerti anche