You are on page 1of 305
COMPUTER SCIENCE with python Textbook for SUMITA ARORA Class XI © Programming & Complitational Thinking © Computer System & Organization @ Data Management je Society, Law and Ethics DHANPAT RA! & Co. COM Pure so SCIENCE THON “ [Textbook XI] Sumita Arora com ANN anion Wwe | DHANPAT RAI & CO. (Pvt) Ltd. EDUCATIONAL B TECHNICAL PUBLISHERS www.worldvideweb.conetare Quality of education depends a lot on the curriculum imparted. Since Computer Science Is a rapidly evolving field, CBSE constituted a committee to look Into existing Computer Science curriculum and recommend a curriculum that is modern, relatively light, teaches timeless concepts like computational thinking, is upto International standards and focuses on problem solving skills than just the syntax. The new syllabus of Computer Science (083) is the outcome of the recommendations by the curriculum review committee. The cbjectives of this new syllabus are laudable — focus on clear understanding of concepts, applications of concepts, problem solving skills, develop computational thinking etc. This book has been written keeping all this in mind. This book adheres to the CBSE curriculumn for Computer Science (083) for Class XI. Based of the syllabus, the book has been divided into four units. Unit 1: Programming and Computational Thinking (PCT-1) Programming and Computational Thinking, unit has been divided in 11 chapters, Chapters 2 to 11. This Unit covers basics of Python, fundamentels, conditional and iterative constructs, strings, lists, tuples, dictionaries, sorting and program debugging techniques. The aim of this unit is to lay foundation of problem solving skills through Python programming language. Unit 2: Computer Systems and Organisation (CSO) Computer Systems and Organisation unit has been divided in four chapters, Chapters 12 to 45. This unit toves basic computer organisation, Boolean tagic, deta representation and insight into program execution. The aim of this unit is to give an idea of how the information is represented, organised and processed Inside a computer Unit 3: Dota Monagement (OM-1) Data Management unit has been divided Into five chapters, Chapters 16 to 20. This unit talks about ‘elotional database concepts, SQL basics, table creation ond manipulation, querying, table joins and > Indexes in SQL. Then this unit talks about NoSQL database and covers basics of a NoSQL database Mongo08. The aim ofthis unit isto provide idea of how data is processed in databases of modern age. Unit 4 : Society, Law and Ethics (SLE-1) Fociety Law and Ethics unit has been divided into two chapters, Chapters 21 to 22. This unit covers Cyber sofety basics and guidelines, guidelines and usage rules for using social networks, threats while Taauine websites and how to prevent/counter these along with how to securely communicate data aim of this unit is to know the challenges In safe and secure use of : etn i of cyber facilities and technologies Apart from the text book, we have also provided a practical book a exercises, Although the text book contains sufficient "ercises, yet the additional practice of exercises given In practi Programming and other concepts even stronger. “Progress in’ that contains additional number of practice questions and cal book will make the foundation of Contents w.worldvideweb.cor 1 q GETTING STARTED WITH PYTHON 1-23 LT Introduction “1.2. Python- Pluses 13. Python- Some Minuses (So Human | Like) 1.4 Working in Python 14.1 Working in Default CPytion Distribution 5 14.2 Working in Anaconda Distribution 9 143° Writing and Compiling Python Program with Command Line fn Linux 15 1.5 Understanding First Program/Script 2 PYTHON FUNDAMENTALS . 21 Introduction BG Python Character Set 23 Tokens 231 Keywords 26 232. Weniifiers (Naraes) 233. Literals / Values 234 Operators 35 235° Punctustors 36 24 Barebonesof'a Python Program 7 25. Variablesand Assignments a 25.1 Creating « Variable 1 25.2 Multiple Asignments $4 253 Variable Definition 16 254 Dyuamic Typing 17 d 26 Simple Inputand Output 26.1 Reading Numbers. 49 262 Oulput Through print Staten 52 RRS 3 DATA BANDUNG 67-120 | 3.1 Introduction ‘ 3.2 DataTypes 321° Numbers 63 322 Strings 71 323 Lists and Tuples 73 324 Dictionary 74 33, Mutable and Immutable Types 33.1 Variable Internals. 78 34 Operators 341 Arithmetic Operators. 81 34.2 Reletionat Operators a5 343 Mentity Operators. 3g ee viii 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

You might also like