0% found this document useful (0 votes)
139 views

Doku - Pub - Sumita Arora Class Xi Computer Science With Python PDF

Uploaded by

SHIVANSH KAUL
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
139 views

Doku - Pub - Sumita Arora Class Xi Computer Science With Python PDF

Uploaded by

SHIVANSH KAUL
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 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!)

You might also like