0% found this document useful (0 votes)
227 views57 pages

New Doc 25 Nov 2019

Uploaded by

Ipsita
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
227 views57 pages

New Doc 25 Nov 2019

Uploaded by

Ipsita
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 57
Agush ‘tondey a Textbook for CBSE Class XI Computer Science — With —— Pythen (As per New Syllabus) PREETI ARORA. Dorel Nero WN etel comity Kulachi Hansraj M CUT AU i| SULTAN CHAND & SONS (P) LTD Educational Publishers 1859/24, Darya Ganj, New Delhi-110 002 Phones, 4354 6000 (100 Lines), 2824 89; Fax (O11) 4854 6004, 2326 4205 E-mail 2 gea@eultanchandebooks.com Buy books online at; www.«ultan-chand.com ISBN: 978-93-87907-41-6 First Edition 2019 * ©All rights reserved. No part ofthis book may be reproduced or copled in any form or by any means (graphic, electronic or mechanical, including photocopying, recording taping, or information retrieval system) or reproduced on any disc, tape, perforated media or any other information storage devica,etc., without the prior written permission of the publishers. Breach of this condition is liable for legal action. Anyone who brings Information regarding any such reproduction will be handsomely rewarded. Publication of Key 10 this book is strictly prohibited. Every effort has boon mado to avoid errors or omissions in his publication. In spite of this, some errors might have erept in. Ary mistake, error or discrepancy noted may be brought to our notice which shall be taken care of in the next edition, iis notified that noltner the publishers nor the author or seller wil be responsible for any damage or 1ss of action to anyone, of any kind, in any manner, therefrom. For faulty binding, misprints or for missing pages, el, tho publishers labity is limited to replacement within one month ofthe purchase by a similar edition. All xpenses in this connection aro to be borne by the purchaser. ‘All disputes are subject to Delhi jurisdiction only Printed at: Goyal Offset Printers, Delhi . S Computer Science with Python for Class XI students aims at providing an in-depth understanding of the CBSE curriculum. It focuses on teaching the Python language to help students learn programming concepts and develop problem-solving skills. With eas and other such tools, the student learns to design the logic for a program and then implement that program using Python. The book contains ample concise and practical example programs along with diagrams and instances from real-life situations. Each chapter consists of tested, debugged and error-free code with screenshots. to-understand examples, pseudo-code, flow charts Based on the CBSE curriculum, this book has been divided into four units: * Unit 1: Programming and Computational Thinking (PCT-1) — Chapters 1-7 * Unit 2: Computer Systems and Organization (CSO) — Chapters 8 - 9 * Unit 3: Data Management (DM-1) — Chapters 10 — 11 * Unit 4: Society, Law and Ethics (SLE-1) — Chapter 12 The CBSE recently announced certain changes to the 2019-20 Computer Science labus (Code 083). The suggested changes have been duly taken care of and additions, wherever required, have been appended to the book. These changes are also available online and can be accessed at sultan-chand.com/ws/python11 Besides, Presentation on Python, Chapter-wise Program Codes, Practical File, Sample Papers, Model Test Papers for practice and Python and MongoDB Software Dump are also available online and can be easily accessed. The book also includes four appendices comprising installation guide to Python and MongoDB, detailed built-in string methods and Viva Voce questions. We are sure this book will prove to be of immense help to the teachers and students alike. Constructive feedback for the improvement of the book will be highly appreciated and gratefully acknowledged. My special thanks are due to Mrs Rinku Kumari and Mrs Alka Gupta for their value additions to the book. Last but not the least, I take this opportunity to thank my publishers, Sultan Chand & Sons (P) Ltd, for their encouragement and assistance in bringing out this book. AUTHOR Syllabus Ww) COMPUTER SCIENCE (NE! CLASS XI Code No. 083 (2019-2020) Distribution of Marks UnitName 1.__| COMPUTER SYSTEMS AND ORGANIZATION. fa 2.__| COMPUTATIONAL THINKING AND PROGRAMMING a 60 30 3._| DATA MANAGEMENT - 1 a es (LAW AND ETHICS - 1 4 SOE i a otal Unit 1: COMPUTER SYSTEMS AND ORGANIZATION + Basic computer organization:description of a computer system and mobile system, CPU, VO, battery, + Types of software:application, System, utility ‘+ Memory Units:bit, byte, MB, GB, TB and PB. + Boolean logic: OR, AND, NAND, NOR, XOR, NOT, truth tables, De Morgan's laws * Information representation: numbers in base 2,8, 16,binary addition *+ Strings: ASCI, UTF8, UTF32,ISCIl (Indian script code), Unicode + Basic concepts of Flowchart + Concept of Compiler & Interpreter * Running a program: Notion of an operating system, how an operating system runs a program, idea gy loading, operating system as a resource manager. *+ Concept of cloud computing, cloud (public/private), memory ard roduction to parallel computing. Unit 2: COMPUTATIONAL THINKING AND PROGRAMMING Basics of Computational Thinking: Decomposition, Pattern Recognition/ Data representation, Generalization Data Abstraction and algorithm. Familarization withthe basics of Python programming: a simplehello world’ program, process of writings Program (interactive & Script mode), running it, and print statements; simple data-types: integer, float, string +, Features of Python, Python Character Set, Token & identifiers, Keywords, Literal, Delimiters, Operators. ingle line & Multline/Continuation statements), Clarity & Simplification of expression ‘ods to manipulate it (concept of L-value and R-value evenit k ot taught explicitly) * Knowledge of data types and operators: ac ‘expressions, operators and their precedence. * Operators & types: Binary operators—Arithmetic, Rel Assignment operators, ‘+ Conditional statements: epting input from the console, assignment statement nal operators, Logical Operators, Augmented | Ihelse,i-elitelse; simple programs: eg: absolute value, sort 3 numbers, and divisibilty f * Notion of iterative computation and control fow-for(range\)k saa interest calculation and factorials, ete. eeblentwe Row cans uggesed pe * Idea of debugging: errors and exceptions; del bugging: pdb, break points, + Usts, tuples and dictionary:finding the maxi ‘ ee minimum, mean; linear search on lis/tupe of rumbe and counting the frequency of elements in a list “sing a dictionary, Introduce the notion of accessi"d elements in a collection using numbers and names. " * Sorting algorithm: bubble and insertion sortscount the number of operations while sorting. *. Strings: Traversing, compare, concat, substring, randint randrange), statistics (mean, median, mode) moduter : 1 COs, tan, > Relational databases: Concept of a database relations attributes and tuples, keys: candidate key. primary key, atternate key, foreign key Degree and cardinality of a table Unit 3: DATA MANAGEMENT. + Use SOL DOLDML commands to CREATE TABLE INSERT INTO. UPDATE TABLE , DELETE FROM. ALTER TABLEMODIFY TABLE DROP TARLE, Keys. and foreign keys to view content of a table: SELECT-FROM: WHERE: ORDER BY alongwith BETWEEN, IN. LIKE, (Queries onty on single table) + Aggregate functions—MIN, MAX. AVG, COUNT, SUM + asics of NoSOL databases. Unit 4: SOCIETY, LAW AND ETHICS — CYBER SAFETY * Cyber safety: safely browsing the web identity protection, confidentiality, soctal networks, cyber trolls and bullying. Appropriate usage of social networks: spread of rumours, and common social networking sites (Twitter, Linkedin and Facebook) and specific usage rules. Safely accessing websites: adware, mahvare, vituses, Trojans, Safely communicating data: secure connections, eavesdropping, phishing and identity verification. Unit S: PRACTICAL S.No. Cy Cun! 1 Lab Test (12 Marks) Python program (60% logic + 20% documentation + 20% code quality) 8 SQL program (at least 4 queries) 4 2 Report File + Viva (10 Marks) Report file: Minimum 20 Python programs and 8 SQL commands 7 Viva voce (based on the report file) 3 3. | Project (that uses most of the concepts that have been learnt) 8 (See CS-Xil for the rules regarding the projects) 5.1: Programming in Python: At least the following Python concepts should be covered in the lab sessions: ‘expressions, conditionals, loops, list, dictionary and strings. The following are some representative lab assignments. + Find the largest and smallest numbers ina list. Find the third largest number ina list. ‘+ Test for primarily + Find whether a string is a palindrome or not. + Given two integers x and n, compute x". = Compute the greatest common divisor and the least common multiple of two integers. ‘+ Test ifa number is equal to the sum of the cubes of its digits. Find the smallest and largest such numbers. 5.2: Data Management: Sal Commands ~ At least the following SQL commands should be covered during the labs: create, insert, delete, select, and join. The following are some representative assignments. : = Create a student table with the student id, name, and marks as attributes where the student id is the primary key. + Insert the details of a new student in the above table. = Delete the details of a particular student in the above table, ‘+ Use the select command to get the details of the students with marks more than 80. + Create a new table (name, date of birth) by joining two tables (student id, name) and (student id, date of birth). + Create anew table (order ID, customer Name and order Date) by joining two tables (order ID,customer 1D and order Date) and (customer ID, customer Name, contact Name, country). are - Getting Started with Python 1). Introduction 32 Python Programming Language 1.2) Features of Python 13. Advantages of Python 24 Installing Python 1S Interacting with Python (Python IDLE) 151. Python Shell 152. Command Line Interaction 153._Python Editor Window (Working in Sctipt Mode) 16 Exiting Python 2. Python Programming Fundamentals 21 Introduction 22 Variables and Types 22) typed 22.2. Multiple Assignments 223 Variable Names 23. Keywords in Python 24 Expressions 25 Operators 25.1 Mathematical/Arithmetic Operators 252 Relational Operators 253 Shorthand Assignment Operators 26 User Input 27. User-defined Functions 2.8. Indentation in Python, 29 Tokens 210 Comments 3. Conditional and Looping Constructs 31 Introduction 3.2_ Introduction to Plan 321 Flow Charts 322 Pseudo-code 322, Decision Tree 33 Program Control Flow 34 Decision-making 341. if Statement 342 else Statement 343. itelif-else Statement 244 Nested if-else Statement 35 Iteration 35.1 forLoop 352 while Loop 26 Nested Loops 3.7 Jump Statements 37.1 break Statement 37.2 continue Statement 37.3. pass Statement 4. Strings in Python 4.) Introduction 42 What are Strings? 43° Creating Strings 44 Traversing a Stting 4.5 Special String Operators 45.1 Concatenating Strings 452. Replicating Strings 45.3 Membership Operators 454 Comparison Operators 4.5.5 String Slicing 47 String Methods and Built-in Functions 48 State and Transition 5. Lists In Python 5.1. Introduction 52 Usts 52.1 Declaring/Creating List 522 Accessing List Elements 523° Traversing a List 524° Alliasing 52.5 Comparing Lists 53 Operations on Lists 53.1 Concatenation 53.2 Repetition/Replication 533 Membership Testing 534 Indexing 535. Slicing 54. Builtin Functions S41 append) 542 extend() 5.43. insert() 544 reverse() SAS index’) S46 update() 547 lent) 548 sorti) 549 clearl) 54.10 count() 55. Deletion Operation 56 Sorting ‘56.1 Bubble Sort 5.62 Insertion Sort 6. Tuples and Dictionary 6.1 Introduction 62 Tuples 63 Tuple Creation 64 Nesting of Tuples 65 Accessing and Traversing 2 Tuple 66 Common Tuple Operations 66.1 Tuple Slicing 6.62 Tuple Addition/Concatenation 663 Tuple Multiplication 6.6.4 ‘in'and not in' Membership Operator 67 Comparing Tuples 67.1, Deleting aTuple 6.8 Dictionary in Python 6.9 Methods to Create a Dictionary 6.10 Accessing Elements in a Dictionary on 6.12 Appending Values in a Dictionary 6.13 Updating Elements in a Dictionary 6.14 Removing an Item from Dictionary 6.15 “in’and’not in’ Membership Operator 6.16 Common Dictionary Functions and Methods 7. Error and Exception Handling In Python 7.1 Introduction 72. Whats an Exception? 7.3. Standard Exceptions and their Handling 74 Handling Exceptions in Python 75 Debugging 75.1 The Python Debugger 75.2 Python Debugger Commands 105 106 108 117-161 117 8 18 12 122 124 125 125 126 127 128 130 131 133 133 134 135 136 136 136 138 138 139, 139 140 145 146 148 163-198 163 164 165 167 168 170 170 172 173 173 7 Ww 179 180 181 18 183 183 184 185 185 199-225 199, 203 204 210 27 218 219 8. Computer System Organization 8.1 Introduction ‘82 Basic Components of a Computer System 821 Input Unit 822 Central Processing Unit (CPU) 823 Memory Unit (MU) 824 Output Unit 83 Secondary Memory 84 Communication Bus 85 Mobile System Organization 85.1 Mobile Processor 85.2 Camera ISP (Image Signal Processor) 853. Display Unit 854 Memory Unit 855 Power Management/Battery Management 86 Software Concepts 86.1 System Software 862 Application Software j 863. Utility Software 87 Concept of Operating System 88 Program Execution } 89 Libraries iy 810 loud Computing 8.11 Parallel Computing 8. Data Representation and Boolean Logic 8.1 Introduction 9.2. Number System 93. Types of Number Systems 93.1 Decimal Number System to Other Base 232 Other Base to Decimal Number System 23.3 One Base into Other Base System 24 Arithmetic Operations in Binary System 25 Internal Storage Encoding of Characters Si ASC (American Standard Code for Information interchange) S23 (SClLndian Standard Code for Information interchange) 3.53 UNICODE (for Multilingual Computing) 96 Boolean Logic 97 Boolean Operators 97.1 AND Operator 97.2 OROperator 97.3 NOT Operator 9.8 Truth Table 29 Logic Gates j 9.10 De Morgar’s Theorems 10. Database Concepts 10.1 Introduction 102 Database Management System (DBMS) 102.1” Need for DBMS 1022 Components of a Database System 1023 Advantages ofa DBM 1024 Dataindependence 103 DBMS Models 103.1 Types of Data Models 10.4 Relational Database 105 Database Keys | 10.6 Relational Algebra 106.1 Union (U) 10.6.2 Intersection (-) 10.6.3 Difference (-) 1064 Cartesian Product (x) 1065 Select Operation (a) 10.66 Projection (r) 106.7 _ Natural Join ()x)) 10.7, NoSQL Database 10.8. MongobB 108.1 Salient Features of MongoDB 10.9 MongoDB Components * 031 conparzn between MongoD8 and bans 10.92 Advantages of MongoDB 20 216 26 26 10.10 Working with MongoDB. 10.11 CRUD Operations in MongoD8, 11. Structured Query Language (SQL) 11.1 Introduction 11.2. Overview of SQL and MySQL. 113 Features of SOL 11. Advantages of SQL 11.5 Classification of SOL Statements 115.1 Data Definition Language (ODL) Commands 11.52 Data Manipulation Language (DML) Commands 11.6 MySQL 11.6.1 | Starting the MySQL Database 117 SQL Datatypes 318 SQL Commands 119 SQL Query Processing 119.1 SQL SELECT Statement 11.82 SQL Operators 11.10 SOL Aliases 11.31. Putting Text in the Query Output 11.12 SOL Special Operators 1.12.1 Conditions Based on a Range—BETWEEN..AND. 1.12.2 Conditions Based on a List—IN 11.123 Conditions Based on Pattern—LIKE 11.33 SQL Joins 11.13.1 Cartesian Product (Cross Product) 11.132 Equi Join 11.14 Union 1115 Indexes 1.15.1 Create Index 12. Cyber Safety 121 Introduction 122 Cyber Safety 123 Safely Browsing the Web 124 Identity Protection while Using Internet 124.1. Ways of Tracking your Identity, 125. Confidentiality of information 126 Cybercrime 1261 Cyber Trolls 1262 Cyber Bullying 1263 Cyber Stalking 1264 _ Spreading Rumours Online 127 Cyber Forensics 128 MaAcT 2000 129. Appropriate Usage of Social Media 12.10. Network Security Threats 12.101 Denial of Service (DoS) Attacks 1210.2 Malware 12103 Viruses 12104 Worms 12.105 Trojans 12.106 Zombie Computers and Botnets 12107. Spyware 12.108 Phishing 12.109 Eavesdropping 12.10.10 Child Pornography 12.11 Safely Communicating Data—Secure Connection 12.12 Identity Verification 12.13. Cyber Safety in a Nutshell APPENDICES ae ‘Appendix A: Downloading and Installing Python ‘Appendix B: More Built-In String Methods ‘Appendix C: Downloading and Installing MongoDB ‘Appendix D:Viva Voce ADDITIONS AS PER 2019-20 SYLLABUS Python Programming Fundamentals (Chapter 2) Computational Thinking (News Chapter) Introduction to Python Modules (New Chapter) Structured Query Language (SQL) (Chapter 11) 307 1 308 323-376 3B 387 383 388 388 388 389 391 392 397-414 To My Parents Shri Gulshan Kumar Arora and Smt. Kamlesh Arora Getting Started with Python 1.1 INTRODUCTION A computer is a versatile machine that can perform millions of instructions in a second, but can neither think nor make any decisions on its own. It requires a program to be written to instruct what needs to be done. Thus, a Program is a set of instructions written in a sequence that guides the computer to solve a particular task. Irrespective of the language being used, the first and foremost thing to be done while writing a program is understanding the problem well, analyzing it, and trying to solve it in a logical manner. The process of writing a Program is called “Programming”. Thus, when we write 2 program, we need to first clearly understand the problem followed by its solution, otherwise we will end up writing incorrect or inefficient codes. Fig. 1.11 Computer Programming Therefore, writing correct codes/instructions in a proper seque extremely important. This is where computational thinking com the actual coding starts for solving a problem, understood first. nce and in the right context is nes into play. Therefore, before the ways in which it could be resolved must be Ur nats savor bepeh ig. 1. ‘omputational Thinking ramming languages have been eveated to meet the needs of programme are erg entre persraret ti of an organization, economy and society by increasing prod wetivty and im Languages die and become obsolete when they £ Me ol he expectatio programmers, and are then replaced and superseded by more power Python is a programming language that h across industrie: id businesses, among pro; MerS ay, ¥ impace Provin, fal 1 oF the "fl Langua stood the test of time and ha ammers and individual us 'S Temai, ers, 1.2 PYTHON PROGRAMMING LANGUAGE When we encounter the word ‘Python’, it reminds us of the fr ightening reptile, However, the programming language has been coined ‘Python’ because just as the reptile has a flexible body, the language too ig easy, simple and highly flexible. @ ™ Python is an open source, object. put ON crientea, high-level programming language developed by Guido van al Research Institute for Mathematics, ed by Python Software Foundation (PSF). janguage, a teaching language created to fuage BASIC, which was developed e: arlier, ‘ython is base Python's Flying Circus, v > 1.3 ADVANTAGES OF PYTHON Apart from the above salient features, Python offers the following advantages: (a) (@) © @ © ao w «) 1.4 INSTALLING PYTHON Ever since the Python language was first developed, it has been becoming popular day by day among programmers. Several versions of Python have been released till now, beginning We shall be working on Python 3.6.5. Before we start working, Python needs to be installed on your system. To install Python, you must first download the installation package of the required Version from the link/URL given below: hetps://www.python.org/downloads/ For installation details, please refer to Appendix A. Python is interpreted, interactive, directly executed, with pre-compiled code. This means that it is processed at runtime by the interpreter and you need not compile your program before executing it. Itis a loosely ‘typed Object-Oriented Programming Language with few keywords (reserved words) and simple English-like structure, and is easy to learn. Itis a free open-source and portable language having a large repository of libraries. It takes less time to develop as Python programs are typically 3-5 times shorter than equivalent Java programs. This is because of its built-in high-level data types and its dynamic typing. Itis extensible/extendable and highly efficient as there is no wastage of time in declaring the types of variables or arguments. Itsupports GUI (Graphical User Interface) and Garbage collection (better memory management). It can be easily compatible with other languages like C, C++, Core Java, etc. Python is used for both scientific and non-scientific programming. Platform-Independent: It is platform-independent and can run across different platforms like Windows, Linux/Unix, Mac OS X and other operating systems. Readability: Python programs use clear, simple, concise and English-like instructions that are easy to read and understand even by non-programmers or people with no substantial programming background. Object-Oriented Language: It is an interactive, interpreted and Object-Oriented Programming Language. Higher Productivity: Since Python is a simple language with small codes and extensive libraries, it offers higher productivity to programmers than languages like C++ and Java. So, you write less and get more done. Less Learning Time: Because of a simple and shorter code, lesser time is required to understand and learn Python programming. GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems such as Windows MFC (Microsoft Foundation Class Library), Macintosh and the X Window system of UNIX. ‘Ample Availability of Libraries: It provides large standard libraries to solve a task. syntax Highlighting: It allows to distinguish between input, output and error messages by different colour codes. Python 1.0. Getting Started with Python Python IDLE comprises Python shell (Interactive mode) and Python Editor (Script mode). Rython 3.6.5 (v3.6.5:£5 8093264, 00 32 pit (nteij} on win32 eee 1 “copyright", “credits” or “license()" for more information. On opening, Python shell shows a welcome message displaying its version and a copyright notice. After this, the command prompt (>>>) followed by a blinking cursor gets displayed, which indicates that IDLE is now ready to take Python commands from the user (Fig. 1.5(a)). Python 3.6.5 (v3.6.5:£59c0932b4, Nar 26 2018, 16:07:46) (HSE V.15|~ 00 32 bit (zntel)} on win32 Type "copyright", “credits” or “License()" for more information. >>> [> start typing here (when we open Python Interactive mode, Python shell with prompt (>>>) gets displayed for the user to enter the Fig. 1.5(a): Interactive Python Shell This is the Python shell, which is part of Python's Integrated Development Environment. The three greater than signs (>>>) are called the prompt or Python command mpt. prompt Learning Tip: Python shell displays the prompt >>> to indicate that it is waiting for a user command to be entered. 1.5.2 Command Line Interaction When commands are entered directly in IDLE from the keyboard, the Interpreter/IDLE is said to be in Interactive mode. In Interactive mode, type the command “Hello World” in front of the prompt (>>>) and press Enter. See what happens. f= S iS bs & > Our First Program So, we begin with our first command in Python Interactive mode as illustrate be} ; lo M: Practical Implementation-1 2 File 14h thet Ovbug Oplone Wivow Help Python 3.6.5 (v3.6.5: vis. 00 32 bit (Intel)] on win32 Type "copyright", “credits” or "Iicense()" for more information, >>> "Hello World" ‘Hello World! 32b4, Mar 28 2018, 16:07:46) (use Fig. 1.5(b): Displaying Message in Python Shell AS soon as we press the Enter key after typin, and the output is displayed then and there. Alternatively, ig our first statement, it gets immediately oe, cu this can be done using the print() function as shown in Fig. 1.5(c) sven be ow, E Fle {64 Shel Debug Options Window Help Python 3.6.5 (v3.6.5:£59c0932b4, Mar 2@ 2018, 16:07:46) ~ [Msc v.1900 32 bit (Intel)] on win3z Type "copyright", "credits" or "license()" for more info mation. >>> print ("Hello World") Hello Yorld >>> print ("Welcome to Python Programming") Welcone to Python Programming >>| ultiple statements typ immediately an ut.This meth sage in front of >>> Fig. 1.5(c}: Displaying Multiple Messages in Python Shell In the above case, we have given two print() statements for displaying two different messages upon pressing the Enter key. Ithas now become evident that we can give commands at the primary prompt and see immediate results. print() is a function which is used to display the specified content on the screen. The content (called argument) is specified within the parentheses. print() statement without any arguments will simply jump to the next line. Python is a case-sensitive language, This means that Python differentiates between capital and small alphabets. For example, Print (P capital) and print (p small) are two different things Yor Python. Whereas print is a valid command in Python, Print is justa word and nota command. This can Be observed by typing the command Print C1 ‘Hello World"). Python will not be able t© interpret it and will show an error as shown in Fig. 1.5(d) given on the next page: Computer:Science with Python-XI : SS Type "o5p00 22 DIET Gately yen wine ae ght", "credits" or “license()" for more info >>> print Hello Wor: (Hello wortam ie ela") call last): E | | i line 1, in i Fig. 1.5(d): Error on Typing Print() instead of print) You must remember that while usin; displayed should be placed within is displayed as it is. 8 the print() command, the message or the argument to be Quotation marks (single ‘' or double “"), then the argument If the argument is not placed within quotation marks, the argument and displays the result. This feature is us an arithmetic expression as an argument, the interpre Fig. 1.5(e). then the interpreter tries to evaluate ed to perform calculations. If we give ter shows its value. This is shown in Practical Implementation-2 Using IDLE as a Calculator just like text/string messages we have given so far, we can also perform mathematical calculations using the Python command prompt. Python 3.6.5 (v3.6.5:£59c093ab4, Har 28 2018, 16:07:46) (NSC VT *| 900 32 bit (mtei)} on wing? Type "copyright", “credits” or “License()" for more information. p> s +8 >>> print (20/4 *5+8-10) 23.0 >>> print (22/7) 3.162057142057149 35> print (3.14*20.8#20.8) 135e, 4896000000003 Fig. 1.5(e): Evaluating Arithmetic Expressions In the above-entered statements, we have performed mathematical calculations using print() statement as well as by directly typing the command without the use of print( ) command. In either of the cases, these statements are immediately executed by the Python interpreter and the output is displayed within a fraction of a second. (TUDE Ch Te LT ~* Consecutive arguments are separated by commas in print() function. When print() is execute the values of consecutive arguments are separated by space between them. So, we can Say that space is the default separator of values in the output. We can also specify some other string ag the separator using the sep argument of print() function (Fig. 1.5(f)). Syntax of print() function: print(value, ..., se , file=sys.stdout) sep: string inserted between values, default, a space. end: string appended after the last value, default, a new line. Type "copyright", “credits” or “License()" for more informatio | 33>, print 00,20, 201) space isthe default separator 20 20.30 2 Brine 20,20, 30,sep="e yorz0"20 353" print (20, 20,20, sep foe'50"" 30 3 peiatit0, 20, 20,2600". Lag 30,20,30 >>3' print (10,20, 30, sep="\n")] “\n! (newline char 35> print (10,20, 30, s0p="\e") ga "bre a ae sera tor Fig, 1.5(f): Use of sep’ with print() Ifwe use the sep argument to specify the separator, then it must be specified after all the values to be printed. Otherwise, the interpreter shows a syntax error. An example is given below: >>> print (10,20,30,sep = '*", 40) ee Syntax Error: positional argument follows keyword argument, End Parameter with print( ) Python's print() function comes with a parameter called ‘end’. By default, the value of this parameter is ‘\n’ -e., the new line character. You can end a print statement with any character/ string using this parameter. The print function uses sep to separate the arguments and end after the last argument. For example, type the following statement using “end” parameter with the print() function >>> print(‘cow’, ‘cat, ‘dog’, sep=,',end="l!\n') and press the enter key. Python shell will execute it and display the output shown below (Fig. 1.5(g)): Tie tt D_06 One Teer Toe Bython 3.6.5. (3.615 {S9c0S32bi, War 28 GOI8s TEIOTT A 46) [MSC v.1900 32 bit (Intel)} ‘on win32 meio Type "copyright, "credits" or "Licensed" for nore information. >>> print ("cow', "eat, ‘dog', sep=', ", ends: cow.eatdogtt pe >>> Atm) GSI a tte Fig. 1.5(g): Use of “end” Parameter with print More About Python Shell The Python Shell Window (as shown in Fig. 1.5(a)) comprises drop-down menus and a Pythy command prompt (>>>) where you can type or enter statements of expressions to be evecuted Itis quite different in comparison to others in the way that it allows to scroll back to previ commands, to cut. copy and paste earlier commands/statements and to modify them. The Python shell window has the following menu items: File, Edit, Shell, Debug, Options, Windows, and Help. The Edit menu allows you to edit the text you type in the shell by applying various editing options such as Undo, Redo, Cut. Copy. Select All. Paste, Find and Replace ‘The Shell and Debug menus are useful when creating larger programs, The Shell menu allows ‘you to restart the shell or search the shell’s log to trace the most recent reset. The Debug ment Provides useful menu items for debugging the Python program in order to trace errors while checking for line-by-line execution of the entered Python statements. The Options menu allows the user to configure IDLE according to the suitability and working requirements. ‘The Help option provides Python Help and documentation. 1.5.3 Python Editor Window (Working in Script Mode) Till now, we were working with the Interactive mode where there is no provision for holding or saving the commands that we typed at the Python prompt. All these commands, along with their output, get cleared as soon as we close the Shell window. This limitation can be overcome by working in the Python script mode where we can save the commands we are typing. This switchover is carried out through Python shell itself. > The File window/option provides various options to create a new file, open an existing file, open a module, save the current module/session. When you click on the "New File” option (Fig. 1.6(a)), 2 new window gets opened, ie, the Python script mode or Python Editor Window, which is a simple and standard text editor where you can type or edit your code. ‘At the time of its opening, this file window is named ‘Untitled’ by default, as shown in Fig. 1.6(b). The name can be changed by the user by renaming the file. 3.6.5 (V3.6. SrfS8C093204, Mar 28 2018, 1:07 *| (usc v.1900 32 Bit (Intel)) on wind? right", “eredits* or “License ()* for more ss Fig. 1.6(a): Selecting File -> New File from Python Shell Sj = cS = bs Sg = = i SS 3 3S Ss Our next step is to save this file by clicking 0 2 proper name for it in lieu of the default n: Fig, 1.6(b): Python Edi C Seria tena bo Ones wesw He peichis if ey first progrsa’} nt feosing Python script Rode") s rink (cit ig advantageous over 1ateract ive rode") ta ae the statenents typed using tis ode’ P P Fig. 1.6(c): ame “Untitled”. cx Options Woo Help at (shis i my first program”) Int("Using Python Script mode") lat ("It is advantageous over Interactive nt(*it saves the statements typed using this mode") Fae, Eat Fermat_ Pan Date modified 15.02.2010 1540 105.2018 a 1sop2018 At rson2018 I tor (Script Mode) Gets Opened Search Pythend6-32 ‘Type the Commands in New Blank File (Script Mode) n File menu -> Save As option, mode") ge Tyee fie folder Fitefotder ie fotser Fite folder Even if you forget to give the extension .py or .pyw while saving your file for the first time, the Python Compiler automatically gives the extension along with the file name. To execute a Python Script file, you have to choose the “Run Module” option from the Run menu or press the function key F5 (Fig, 1.6(e)). More About the Script Mode While working in the script mode, when you enter the statements to be executed and press Enter key, you won't automatically see the results the way you would see in the Interactive mode. To see output from a script mode, you have to run this script and/or invoke the -print() function. t my first progran’ ython Script mode" dvantageous over Interactive mode") Python 3.6.5 (v3.6.5:£55c0932b4, Mar 26 2018, 16:07:46) |” Msc v.1900 32 bit (Intei)} on win32 ‘Type "copyright", “credits” or “license()" for more intor mation. >>> RESTART: C:/Users/preeti/appData/Local/Programs/Python/P ython36-32/program!.py This is my first program Using Python script mode It is advantageous over Interactive mode Tt saves the statements typed using this mode Fig. 1.6(F): Output of the Program Displayed Inside Python Shell It must be remembered that even if we enter the print() statements in the script mode, the output shall be displayed only in Python shell. 1.6 EXITING PYTHON In order to exit the Python command prompt, click Ctrl+Z and press Enter key or type quit() or exit() function/statement and press Enter key. POINT TO REMEMBER If exit() or quit() does not work, then alternatively you can type the following commands: import sysi sys.exit() Getting Started with Python! r _,. of instructions written using 2 programming language js termed 5 sees: mmming language. It uses concise more codes and develop more complex progr 18 2 powerful and flexible progr programmers to writ AMS in > Ris a piattorm-independent programming language > yah interpreter executes one statement (command) at a time: 5 > Python provides two different ways to work with— Interactive mode ANd Script my, Program and theo, typing one or mor, vve mode does not save commands in the form of a 5s 8's Gisplayed as soon as we press the Enter key after Interactive mode Is sultable for testing code. > Python ode, PUL lace © commands 's 2 case-sensitive language. Thus, » Python ts an > Python's ints Ram and ram are two different ames in Pray, "Wthon, terpreted language. 7 “roctive interpreter is also called Python Shell, "Ms written in Python an > Wrong indents > The progr 'e easily readable and ston can give rise to syntax error(s). “Mest Python editors will automatical Primt() statement outputs an entire (complete) ine and then goes to the * Script mode is useful for crea All the programs in Python ar understandable, ly indent the statements, FILLIN THE BLANKS u_Pr 7m 2 Prion was created by 8. To start Python from the command prompt, use the command Pin Puy!hon 9. Python programs are saved using the + py or Puy exten’ 10. Python programming can be done in _ 9 tr). 2 ye and eit pie modes. ANSWERS TO FILL IN THE BLANKS, 1. Program 2. Guido van Rossum 3. Python 4, Case-sensitive 5. Interpreter, runtime 6. Platform a 8. Run Python 9. -py, -Pyw 10. Interactive, Script SOLVED QUESTIONS 1. What is Python? Ans. Python is a high-level, interpreted, dynamic, Object-Oriented Programming Language that supports GU! programming. 2. Why is Python interpreted? ‘Ans. Python is interpreted because the program is processed at runtime by the interpreter and you do not need to compile your program before executing it. 3. Who developed Python? ‘Ans. Python was developed by Guido van Rossum in the early nineties at the National Research Institute for Mathematics in the Netherlands. 4. Why is Python easy to learn? Ans. Python has relatively few keywords, simple structure and a clearly defined syntax. This allows the student to understand and work easily in a relatively short period of time. 5. Write any one feature of Python library. Ans. Python library is very portable and cross-platform compatible with UNIX, Windows and Macintosh. 6. Is Python a compiler language or an interpreter language? [HOTS] ‘Ans. The normal execution of Python program is interpreted. However, subsets of the language can be compiled. 7. Python Is a free and open-source language. What do you understand by this feature? ‘Ans. That Python is a free and open-source language signifies that we donot have to pay anything to download it. Also, being an open-source language, its source code is also available if we wish to modify it. B. State some distinguishable features of Python. ‘Ans. Python is a modern, powerful, interpreted language with objects, modules, exceptions (or interrupts) and *" automatic memory management. It was introduced to the world by Guido van Rossum in the year 1991. Salient Features of Python are: ‘+ Simple and Easy: Python is a simple language that is easy to learn. + Free/Open source: Anybody can use Python without the need to purchase a licence. + High-level Language: Being a high-level language, it can be easily understood by the user without the need to be concerned with low-level details. + Portable: Python codes are machine and platform-independent. + Extensible and Embeddable: Python programs support usage of C/C++ codes. ‘+ Standard Library: Python standard library contains pre-written tools for programming. 9. Distinguish between Java and Python. ‘Ans. Java and Python can be distinguished on the following bases: 1. Python programs run slower than the Java codes, but Python saves much time and space. Python programs are 3 to S times smaller than Java programs, 2, Python is a loosely-typed dynamic language as no time gets wasted in declaring va Java. Python is easier to learn than Java, ble types as in = 2 rE} cz} = S c= i. i a diference between interactive mode and script mode in Py, 10, What Is the mode, instructions are given in fo of Python Prompt (>55)in oan \ ee beri instructions and shows the result there itself, Shy \ cout the Python instructionsare stored ina file, generally with .p Y exten; io .d instructions are known as Python scri ay Inscript mode, peers, in one go asa unit. The save 11, Give the output for the followin 1, print ("Hello") 2, print (5.5) 3, print (446) Ans. >>> print (“Hello”) Hello >>> print (5.5) 5.5 >>> print (446) 10 UNSOLVED QUESTIONS 41. When was Python release 2. Who developed Python and which two any 3. Is Python case-sensitive? 4. What is IDLE? 5; Diferentiate between displaying and printing method in Python. 5: Briefly explain the salient features of Python, 7. What do you understand by \guages contributed to Python as a Programming langue, Tama class xz- , ‘my lan 'euage? Python Programming Fundamentals 2.1 INTRODUCTION In the previous chapter, we hi interactive mode and Script mode. st definitions and commands. These definitions ar the Python interpreter, which is known as Python Shell Python syntax. P ‘A Python program, som Before moving further, we shall discuss users and the system sl that defines how 1m in Python, you mus want to write and run your prograi ‘The syntax to be discussed constitutes the concept should understand first In Python programming language, data variables is not required and memory man: Whatever values we assign to the variables, the data type of the value, Hence, itis said t [cm ata ty 2.2 VARIABLES AND TYPES ‘A variable is like a container that stores values that you ‘can access or change. A variable, as the name suggests, has been derived from the word “vary” which states that ‘a variable may vary during the execution of a program, ie, the value of a variable keeps changing during the program execution. In Python, every element is termed as an object. Hence, a variable is also an object in Python. ave discussed the two modes of int imes called a scrip evaluated and the command »ython syntax. should write and interpret + familiarize yourself wit of variables an‘ yypes are inbuilt an‘ jagement is automatically done by P) the data type of the variable will ¢hat Python supports dynamic typing pes are inbuilt in Python and, hence, it supports dynamic tYPINS. ‘ETM: Variables provide a way to associate names with objects, refers to a set of st a Python program. h its syntax dts data types that you \d unlike in C++, declaration of -ython. be the same as ‘am a Pythor varble My name ix andl can point ton arbitrary cbject. In this case to an int object. q 2.12 Variable in Python. : Every variable hy abe wee its value. EvEDY V Tarowet mn manipulates It ofthe va haviour re the va sa riable. and bel ~ ig. 22) Tir wn in te stave aagram. Fie named X, 3 tesshe value 3 to variable F Fg.22:StateDigram ayy : cally assign 2 ¥2 , wil toma isan integer: 3 ee x= 10 (72 10) il display 10 as the output in thep Se Prone) and press he Bue It a ee and then wrt shell (Fig. 23). Fie ae Seal Does cossape, Mar 26 71 8, 1 C yenen:3.6:9 500 intel) }_ on wind: ™ for more infor sev 00 32 ie (aneg 8 Meticense 0" £0 i type "copyright", Fig. 2.3: Value of Variable x Gets Displayed The above behaviour exhibits that variable x has been given a value 10, which is stored insides ‘memory location withthe name x. This statement shall store 10 in x but does not get displayed until and unless we type x (>>>). n typing x, value 10 shall be displayed as the output. ‘ats take another example of working with variables. Consider the following code: >>> y >>> 2 >a >>> x display the value a but for displ: the values of ve pri playing the ve sighed toa varahie. 0, oeeMeMt explic single line. The co ity, ed tO ‘able. The pri ¥. print() statement is us mma () separates the Ta = ment can print multiple values 0” @ eS and variables th at are printed. ee ty Avaria a) ke B) 1 C1 Now, save the code with a suitable file name with extension .py and then run it (Ran -> Ran Module or press FS). Fython 3.6.5 (v2.6.5:f58c0932b4, Mar 22 2018, 16:07:46) [MSC v.1300 22 bit (zntel)] on windz Type “copyright", "credits" or "license" for nore information. >>> RESTART: C:/Users/precti /appoata/Local /Progza s/Python/Python3é-22/progi_chap2. Fy x is: 4 y is: 5 zis: e >>> Fig. 2.4: Running Code inside Script Mod= Let us understand this code line by line: 1. x starts with value 3 and y starts with value 4. 2. In line 3, a variable z is created and equals x + y, which is 7. 3. Then the value of z is changed to equal one more than it currently equals, changing it from 7108. 4. Next, x is changed to the current value of y, which is 4. 5. Finally, y is changed to 5. Note that this does not affect x. 6. So in the end, x is 4, y is 5 and zis 8. A variable/object has three main components: A) Identity of the Variable/Object B) Type of the Variable/Object () Value of the Variable/Object Fig. 2.5: Components of a Variable ATA) cour Mu CTL} fated co ofthese asso" pie/object ariable in s of he addres each discuss We shall now taentity of the Varia Je object's (¥ ted. T piscase) adress inte MEMOTY WICH dog itrefers oth ymbject can be checked using she "Chay once it has been creat syntax: Forexample,>>>id (*) ee be Dt G930b4, Nar 26 2018, S65 (v3.6.5:£590093. ere fe canted} 08 nae v.1900 32 DAE, oe ese a" python 7:46) B type “copyright”, je information. Address of memory location storing value 10 Fig. 26: Address of aVariable Using id() Method 8) Type of a Variable Object: By type we refer to the data type of a variable. In Python, each value is an object and has datatype associated with it, Data type ofa value refers to the value it is and the allowable operations on those values. A data type in Python can be categorized as follows: | Mappings | - Imteger i lating Complex Dictionan | Sst ree Strings Tuple List ye! Python supports th ‘numbers and comp) cun your statement. * Integer/iong, floating point oa int (int ‘cm: Range 9 ‘unlimited ean (b) flo Here are Lot reg tnt (integer): Integer represen ‘a } Python. T jong integer has ange ofan integer in Python can be fom memory crm: Tpraras3eae to 2147483647, and! Simited range subject to available Floating point nt number earning Th art of a floating pain fan also beO (ze) (b) float (floating point numbers): umbers denote real numbers or floating Point vplues (Le, numbers with fractional part) Floating fare written with a decimal point point numbers the fractional numbers. that separates the integer from offloating point numbers are: 3:14, 62023, 432, 6.0 28879.26 ete Exam “Gi A valve sore os a oating point numberin Python can Nave Fraximum 53.its of precision. thas a re Ble a (6) Complex numbers: Complex numbers in python are made up of pairs of real and imaginary numbers. They take the form x + Vor x+yl where ‘x's afloat and the real part ofthe complex ‘number. On the other side is ¥] Where ‘y's a float and J or its lowercase indicates the square root of an Imaginary number, -1. This makes ‘y’ the imaginary part of the complex number: s Here are some examples of complex numbers: (p ox = 2459 y >>oprint (x.real, x-imag) 2.0 5.0 (i) >>>y = 4-23 >>>print(y.real, y-imag) | 4.0 - ynly (ii) >>>z =x 4 fe } >>oprint (2) on. (6 +33) nt. int or “license()" for more ; inforna, ti >>> print (x.real, x.imag) 2.0 5.0 so yea - 25 >>> print (y.real, y-inag) 4.0 -2.0 >> z=xey Fig. 2.8: Handling Complex Numbers Complex numbers are not extensively used in Python programming. 2. str (String): A string is a sequence of characters that can be a combination or numbers and special symbols, enclosed within quotation marks, single or double gS (‘or"” or” “”). These quotes are not part of the string. They only define the staring * \ “ending OF ie irng, A string may have any character, sign or even space in between ie Forexample, >>>str = "Hello Python” >>>print(str) Hello Python 3. bool (Boolean): Boolean data type represents one of the two possible values, True or Fs B two possible values, True or False 5 Any expression which can be True or False has the data type bool. Baoy cspress on wmichican|bey Ucn rae 'a type b ing gets displayed, Alternatively, print() statement can be used to display None value a ters, ne {Triple shown below g and e2) hem. i Fle Est Shell Debug Options Window Hep Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16: se. 6) [MSC v.1900 32 bit (Intel)] on win32 z None >>| : Handling None Fig. 2.1 | 2.2.1 type() If you wish to determine the type of a variable, i.e,, what type of value does it hold/point to, then type() function can be used. For example, >>> type (10) >>> type (8.2) >>> type (22/7) >>> type ("22/7") >>> type (-18.6) >>> type("Hello Python") >>>. type (True) ———> >>>_ type (False) ——___> The Boolean argument given to type) function should have T (capital letter) for True and F (capital letter) for False; otherwise >>> type (825) >>| it will generate an error. The above code can be alternatively typed as follows: [SC v.1800 32 bit (Entel)) on wind? Type “copyright, “credits” or "license()" for more inform jation. >>> x= 10 >>> type (x) >>> x = 30.5 Let us take another example for type(). Different types of values can be assigned as under: xyZ = “Hello” w=18 pi = 3.14159 = 3,241.55 type (xyz) type (w) type (pi) type(c) Fig. 2.17; Use of typed Function ©) Value of Variable/Object: pulated later Variables provide a means to name values so that they ean be used and 2 9 : jgnment operator (=). Tis process i also termed ‘To bind value to a variable, as building of a variable. ‘The assignment operator assigned to variables using assignment ope Values are For example, consider the statement, Soprine athe) |PEAnE (Hat ‘The statements shall yield the output as shown below ese ce ot ee gi zs DS python 3.6.5 (v3.6. 59c0932b4, Mar 26 2018, 1 aytnen 3.65 ee ee inten on wine” G07 hy tase 100 tae or siieanse” for | erage ate ee edred a) Python associates the name (variable) Maths with the value 67, i. the In the above example, ned the value 87 or, in other words, the name (variable) Maths name (variable) Maths is assigr | gefers to value 87. Values are also called objects. In an assignment statement, the variable that is receiving the value must appear on the left side of the = operator, otherwise it will generate an error. ving Forexample,>>>87 = Maths #this is an error 3 Bee d only one variable on the le : hand ‘ ssi 3 There sh ible is called the Left value or th ae seme oe enment operator. This right-hand side of The statement value R-value eee mn assignment statement, hen the interpreter encounters gee ns the value to the left-han« ced ease a sn rie anda he ecto et et 4 “Sao eva) oss Variable firs enor pata scape rable ASSIGNING a vorabie vine \e g ‘There o— | | a : 1 ia 5 i aid oe 0 () en ‘onsider two variables, x and y, and we th i rome {ype the following assignment statements: ble is assigned 3 as sa value, y= 3 Avariable'y tsalso ass refer to Fig. (0) ned only refer tig yen ae 3:80 NOW y shall be pointing to # variable ‘'y’is assigned another value 2, refer to Fi i ig. (i) Now the final value of y becomes 2 and x remains 3 as assignment operator erases the previous value and assigns new value to the variable ‘y. Thus, it becomes evident that we can use ‘assignment operater for assigning values to a variable along with their reassignment 2.2.2 Multiple Assignments In Python. we can declare multiple variables in a single statement. It Is used to enhance the Feadability of the program. Maltpte assignments in Python can be done in the following two ways (0 Assigning multiple values to multiple variables: varl, var2, var3_. . varn = valuel, value2, value3_... valuen This statement will deciare variables varl, var2. respectively. For example. Another statement. x, (@) Assigning same value to multiple variables: varl=var2=var3s . . =varn = valuel This statement will declare variables var1. var2, .... varn, all with value as value1. For example, total varn with values as valuel, value2— valuen = ‘Meeting’, ‘Mon’, ‘9° binds x to 2 and y to 3. ke = count = 0 ¥-1500 32 Bit (intel)] on wins Type "copyright", "credits" or "license()" for more informat ion. E,YeZ/P = 2, 40, 34.5, "Vinay" £,¥/2,D 40, 34.5, "Winay") zty x-¥ a=b=c=-55 2b, -55) Fig. 2.14: Multiple Assignments in Python 2.2.3 Variable Names ‘There are certain rules in Python which have to be followed to form valid variable names. Any variable that violates these rules will be an invalid variable name. The rules to be followed are: (@ A variable name must start with an alphabet (capital or small) or an underscore character (_). (i) A variable name cannot contain spaces. Avariable name can contain any number of letters, digits and underscore (_.). No other characters apart from these are allowed. (iv) A Python keyword cannot be used as a variable name. Ss By € = SS 5 rs = a Name cannot start 4) is not allowed 3aGraph special symbol a FirstName Dots are not allowed fa te 4 p08 Keyword not allowe exampl wile (hile) variables: al implementation on V + two numbers and find their sum and product Example 1: To inp! Solution: tae er second number:") 2.3 KEY a: 8 ‘We know that time taken to cover a distance is calculated as: In this problem, we need a data value >> import keyword [>>> print (keyword. kwlist) ['ralse', 'None', "True', ‘and', ‘as’, tassert', ‘break', ‘class', ' continue’, 'def*, ‘del', telif', ‘else’, ‘except’, ‘finally', ‘for', ‘trom’, ‘global’, 'if', ‘import', 'in', 'is', ‘lambda', ‘nonlocal', tmot','‘or', ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with', ‘yi je1d" >>> | ine ca Fig. 2.15: Keywords in Python 2) = r= 5 = 3 BS = Fe iS — = wy a of value(s)» : = 2.4 EXPRESS! smvnain of NC valu = aie enerates 4 ee roe 1 ty contail the m eee e the speci? btractic Oe emant samples Cal . represent sim truttiplication. a Stee p 10/2-3 a wee 8 s247- ene seat Expressions to Equivalent Python EXPressiong averting Mathemal ra are not used in th gas. von at we use im algebra are not used in the same gy rent operators The mathematical express! ramming languages. requires different o = ing | s, req different operators ters. In maths, you use diffe as other pro for mathematical calculations, On qe hand, Python, as well mathematical operation. For example, : Ptsctrac expression | operation Being Performed ration Being Performed | Programming Expression SS ae Als : s times B ena) 3 times 12, 3°12 ay 4 times x times y atxty When converting some algebraic expressions to programming expressions, you may hae y insert parentheses that do not appear in the algebraic expression as shown in the table ga below: Algebraic Expression Steen Y=3°x/2 Which we will discuss 2.5 OPERATORS Operators are sp oe tors are special s ibols whic} lich can be valu Mr ae wat 2 Variables, Operators wen applied on onecay Perator can Detar are applied on operanil) Operators are ee form ai rently on different data tyP® riables, when us Arithmetic, Ret, em ae ost important element used is the ‘Operato, ee) eee Tee ression, ee ‘ational, soe ana Assignment, Value 3 R W For exa Concater Strings ¢ give the have to le given ator (5) es: 2.5.1 Mathematical/Arithmetic Operators Ena subtraction Division * Remainder Modul Exponentiation uw Integer Division For example a 34 34 >os17%5 223 @ pooietss 40 ss7.0//2 30 Concatenating Strings strings can be added together with plus (+) operator. To concatenate the string give the statement using concatenation operator (+) Output: >p> “Hello” + “Python” oPython 8 e 9.33323333333334 >>232 sss26 256 o>o3/l2 #subtraction fvaltiplicat #integer Divisio #Modulus texponentiation #exponent iatio: “Hello Python’, Oustpot nowt thre! 3 howat ? Senilarty, eamering “FP * 5 wAll yield ' Ourprut, ellohellohellohel 1 (nary and Binary operators: An operator can be termed as ting. upnn the pumber of operands it takes N unary operator takes only one operator takes twn operands. For example, in the expression 64) « ae be» unurry minus and the second minus sign is a binary minus. TI he muttiptc, operstars in the shove expression are binary operators. Atlon ang é oe “at Precedence of Arithmetic Operators ‘0 (parentheses) “ fexponentiation) ~ {negation) decreasing order | (Bresion) /) integer division) * (multiplication) % (modulus) + {xS8ition) - (subtraction) More Examples of Arithmetic Operators: tvaluate the following expressions: (1) 12+3°4-6/2 (2) (12 +3)*4-6/2 (3) 12 +3" (4-9) (6) 12+ (2 4-6)/2 (5) 12 * (3% 4)//2+6 (6) 12% 3 ** 47/545 Solution: (3) 12+3°4-o/2 (2) (12 +3) * 4-6/2 (3) 12+3* (4-9/2 242¢12-6/2 =15°4-6/2 1243" (22 #120 12-30 =60-6/2 = 12+ (-6)/2 = 24-30 = 60 - 3.0 = 12-30 2210 = 57.0 =9.0 (4) 124 (3% 4-6/2 (5) 127 (3% 4)//2+6 (6) 12% 37 4//5*6 = 12+ (81-6)/2 = 12°3//2+6 = 129681//5 +6 #126 75/2 = 36//2+6 2//5 +6 #120375 = 1846 +6 495 =24 =8 2.5.2 Relational Operators i Relational operators are used for comparing two expressions and results in either Ie false In an expression comprising both arithmetic and relational ‘operators, the ‘arith gperators have higher precedence than the relational operators, ad mary g nd angen First mp lage A and eeap Md adage | ” der F 4-6/2 *4//5+6 4-6)/2 c ig //5 +6 5+6 ue oF metic For example, syntax: Town as Comparison operators and yield value, True of False a Roa Pres oer caer rao Te False ee code e Falco True 55721015 True True ateater than soot S5>'Hello'“Goodbye! Tue Tue >5>10>10 355'Goodbye'>'Hello False False less than equalto >5>2<=5 >>>'Hello-e= Goodbye! True False >op7eat >>>'Goodbye'<=Hello False Tie ‘greater than equal >>>10>=10 s>'Hell’s='Goodbye to True True >>10>=12 >>>'Goodvye'>=Hello False False <> notequal to >>>10l=11 >>>Hello!="HELLO Twe True >>>10!=10 >o>'Hell False False equal to >poprint ("23 < 25 >>oprint. >>pprint ("23 < Lto equal zo >ooprin >>>print ("23 != 25") 23! When the relational operators are applied to strings, strings are compared left to right, character by character, based on their ASCII codes, and also callec ASCII values. print ("*hello! < ‘Hello’ :", ‘hello' < Hello") hit > ‘hello") #not equal to print ("hit > ‘hello’ : Output: ‘hello! < 'Hello' : False ‘hit > ‘hello’ : True ‘ rete) ee prs not True. 5 -nce of Logical Operators : lb Decreasing 2.5.3 Shorthand Assignment Operators ment operato: or an augmented ment. Different augmented A Shorthand Assignment Operator (or compound ass ;perator) is a combination of a binary_operation-and assignment operators available in Python are as follows: Note: We assume the value of variable x as 12 for a better understanding of these operators. $2 added and assign back the resut to left operand >39x#=2) The operand/expression/constant written on RHS of operator wil change the value of x to 14 x will become 10 xwill become 24 x.will become 6 x will become 0 = subtracted and assign back the result to left operand ruitiplied and assign back the result to left operand bis equivalent to a =b Learning Ti 1 Same eperator may or may perfor a sifeen fonction” depending on the datatype ofthe vlog ‘ewheh tis apled 2.Dvsion opener differenti fi Vales behaves 'y on integer and float inp. int the 2.6 USER INPUT While writing a program, we need to fetch some input from the user. the user are fetched and stored in the variables. Python provides three Important functions for getting user's input. 1, input(): input() function is used to get data from the user while working with the script mode. It enables us to accept an input string from the user without evaluating its value. The function input continues to read input text from the user until it encounters a new line. The values inputted by (a) Let us see a simple example to fetch user’s name and to display Welcome message concatenated with user name. The input() function takes String as an argument. During execution, input() shows the prompt to the user and waits for the user to input a value from the keyboard. When the user enters value from the keyboard, input() returns this value to the script mode. In almost all the cases, we store this value in a variable. When the first statement of the above example is executed, the user is prompted to enter his/ her name. The name entered by the user is stored in the variable name. After this, the variable name gets combined with the ‘Welcome’ message and can be used as many times as needed. LB prog2_chap2py -C/Users/preeti/AppData/local/P_ - Fae_{et_ Format Rum _Optent UWndow Hele name = input (‘Enter your Name print ('elcome', name) python 3.6.5 (v3.6.5:£55c093ab4, Mar 28 2018 *| 7 16:07:46) (SC v.1900 32 bit (zntel)} on w in32 ‘Type "copyright", "credits" or “license()" £ or more information. >>> RESTART: C:/Users/preeti /AppData/Local/Prog rams/Python/Python36-32/prog2_chap2.py Enter your Name : Sonia Welcome Sonia >>| eres input() function is not highly recommended by the programmers since it always accepts input in the form of strings and hence manipulates number as strings only and does not generate the desired result. 3 5 = Fy By i 5 = S — Es 33 30 and 40 ar 3.08.65: ¢34c0810B4, mar 28 20 Tome vines 33 bit. tineeis} oe wins | 2.7 USER-D credits" of “License()* for more t4/Appbata/Local /Prograns /Pytn 99, chap2. py > How t MOGs 8 Need to modty our program using another function int(), _— #1) function converts the neg ae ng value into numeric value and shall store the value 30 def functi “tnenber and nat asa ring Thus we wil obion he desired result as 70 (sum of 30 and 40) \ 2 eval) This fun Aa erase the value ofastring takes a string as an argument, Scauatt GI WRG @ Gumber aed eturns the numeric result sewed ‘he joven argument is nay g ring oF if it cannot be evaluat fed aS a number, then eval() Stateme that the ue 30 40). nent, ral() Error Argument cannot be evaluated as a number In ll of the above programs, we have used built-in functions available in Python library for performing numeric and string operations. Let us discuss another way of writing codes using User-defined Functions. 2.7 USER-DEFINED FUNCTIONS ‘A function is a group of statements that exists within a program for the purpose of performing 3 specific task. Instead of writing a large program as one long sequence of instructions, it can “Ge written as several small functions, each one performing a specific par; of the task. > How to Define and Call a Function in Python ‘A user-defined Python function is created or defined by the def statement followed by the function name and parentheses (()) as shown in the syntax given below: Syntax: def function_name(comma_separated _list_of_parameters) Function Definition (ache [Statements below def begin with four spaces. This is called indentation. It is a requirement of Python. that the code following a colon must be indented R zx Practical Implementation=1 Let us define a simple function (which does not return any value) by | fane1 ("and call the function, The output of the function wtf ft the ey | Python” (Fig. 2.17), Mtn yy Ae My ney, hy ‘nt Fae {dt Shel Detog Options Window Help Python 3.6.5 (v3.6.51£59c0932b4, 900 32 bit (inten) | on wing ot tunel (7 an or store Lntonsaoy, print ("I am learning Functions in python) * Function bp yitan >>> (func 0)» Funetion call 1 am Tearning Functions in Python > Output >>| Fig. 2,17: Function Definition (Interactive Mode) Practical Implementation-2 To write a user-defined function to print a right angled triangle. 12 progs,chap2py - C/Users/preeti/AppData/Local/r.. - © [NEI] Fae {et Format Run Options Window Help def triangle(): ° print ("*") print("* *) print("* + #*) Print ("* + + sy) — Tie Eda_Shell_ Debug Options Window Help Type "copyright", "credits" or “license()" for mo “ re information. C:/Users/preeti/appbata/Local/Programs/ | on 32/prog4 chap2.py >>> triangle) » Invoking the Function ae tae teas nd breadth as the arguments — ‘explicit beginni rely on this indes Indentation is shifting ites (blo ction; they have to another statement. In Pyth coup of statements which » its above statement (let us call ment A. This concept is used © te ereated as a unit. Ifa suite (let us call it) A), then execution of loops (covered later) the following figure: ). The concept of inde (Under A. at the same level as B and C) Aon Here we take a simple example with “print” command. inl show “indentation ery fanci (I! af = stow the def Fane gented block sna tanctionhasbean ded when W my below det) nd hen medic ed an ind expect operators: la une 0) tation Results in Error Generation (a: Improper Indent Fig, 2.18: Ip fore the print() function, at prop xde work successfully. er indentation bet ‘The above error an be removed by making proper indentat Jeast one indent is required to make your co (Zeglaiy iliemret/AopOvtocaProgoms/rynon= = =| eer erecta ete eae et I a ene et ee rH = yt 3-4-5 W9.6.5FE59C0S0054, May 282018, 16:07: - 2) tw v-tn00 38 ie tame on wanda, ape “cepytight*, "credits" or "license ()" for more 2.10 ¢ RESTART: C:/Users/preeti /Ay ra/Local | ee preter gio ec rsmnasrer ae 1 am learning ions in Python aa Pythor | under: 7 (om ah pt that is meani : i enti ningful to the interpreter. The dentifiers: The name of any vata keywords, literals, Operators and del or modi i = ule is called an identifier. Keywords: The reserved words of Python which have a special fixed meaning for the interpreter are called keywords. No keyword can be used as an identifier. The Python keywords have already been listed in the previous topics. Literal: A fixed numeric or non-numeric value is called a literal. Examples of literals are: 2, -23.6, “abc’, ‘Independence’, etc Operators: A symbol or a word that performs some kind of operation on given values and returns the result. Examples of operators are: +, -, **, /, ete. Delimiters: Delimiters are the symbols which can be used as separators of values or to enclose some values. Examples of delimiters are: () () [], Note: # symbol used to insert comments is not a token. Any comment itself is not a token. For Example: Observe the following script and enlist all the tokens used in it. For each token, write its category too. #Identify tokens in the script print ("x, y, z are:",x,y/2) ion rnd x Identifier/Variable y Variable z Variable print Keyword = Delimiter/Operator t Operator ; 68 Literal 12 Literal “x y,z ar Literal 2.10 COMMENTS Comments are statements in a script that are ignored by the Python interpreter and, therefore, have no effect on the actual output of the code. Comments make the code more readable and understandable for human beings. This makes the revision/modification of the code easier by the original author of the code and also by some new author who has been assigned the responsibility to modify it, Comments are not necessary in a script, but these are highly recommended if the script is too complex or if it is to be reviewed by multiple people over an interval of time. ‘A comment in Python starts with a hash symbol (#) anywhere in a line and extends till the cad of the line. The following code contains two single line commrentsr # This is a single line comment x=10 y=x+100 # value of x + 100 is assigned to variable y print (y) ene C eu uC el ™ | Fanon BYTES A python program can contaln various components ike expressions, statements, comments, 7 ‘, and Indentation, Pctons No, > An expression Is a legal combination of symbols that represents a value. > A statement Is a programming Instruction, > Comments are non-executable, additional Information added in a program for readability, > In Python, comments begin with the hash (##) symbol/character. } A variable in Python is defined only when some value is assigned to it, > Python supports dynamic typing, /c., a varlable can hold values of different types at different tim es, } A function is a named block of statements that can be Invoked by its name. > The input () function evaluates the data input and takes the result as numeric type. > Output is generated through print statement. An expression isa valid combination of operators and operands. Operands are the objects on which operaty are applied. = > Arithmetic, relational and logical operators are used for performing computations in a program, > Astring isa sequence of characters. To specify a string, we may use single, double or triple quotes. > The operator + (addition) applied on two string operands is used for concatenating them. Similarly, the operat + (multiplication) is used to repeat a string a specific number of times. > When relational operators are applied in strings, strings are compared left to right character by character according to their ASCII values. > While evaluating a Boolean expression Involving ‘and’ operator, the second sub-expression is evaluated oniyif the first sub-expression yields True. > While evaluating an expression involving or operator, the second sub-expression is evaluated only ifthe fist sub-expression yields False. > Avariable is a name that refers to a value. We may also say that a variable associates a name with a data object such as number, character, string or Boolean. } Values are assigned to variables using assignment statement. The syntax or assignment statements Is as follows Variable = expression where expression may yield any value such as numeric, string or Boolean. > Iman assignment statement, the expression on the right hand side of the equal to operator ()is evaluated ané the value so obtained Is assigned to the variable on the left hand side of the = operator. } Avariable name must begin witha letter or_(underscore character). It may contain any number of letters dats ‘or underscore characters. No other character apart from these is allowed. > python is case-sensitive. Thus, marks and Marks are different variables. > The shorthand notion for a = a b is a In Python, multiple assignment statements can be specified in a single line as follows: , , .. = , , .. > Akeyword is a reserved word that is already defined by Python for a specific use. Keywords cannot be used for any other purpose. SOLVED QUES THON S = 1. Consider the following statements in Python interpreter and describe the output/statement required: (@) Print a message “Hello World”, (b) a = 10 b= 12 cath print (c) (©) To retrieve the data type of the inputted string “Hello” stored inside the variable ‘a’. (d) To describe the data type of variable ‘b’. {e) To retrieve the address of variables a and b. (A) State the output: a@=b >ood >>ob >>>id(d) >>>id(b) (g) a= “Hello” atio (h) To display the value for a’, a? and a* @a-15 b=4 a/b a//b (@ To swap the values of two variables, a and b, using multiple assignment statements. Ans. python 3.6.5 (v3.6.5:f88c0932b4, Mar 26 2016, 16:07:46) [MSC v.1900 ~ 32 bit (Inte1)] on win32 Type "copyright", "credits" or "license()" for more information. >>> print ("Hello World") a) Print a message Hello World p> a= 10 >>> b= 12 docs ath >>> print (c) 4b) output displayed 22 >>> a = "Hello" >>> type (a) 4c) Retrieve the datatype of variable a >>>_type (b) co) >>> id(a) #/@) Retrieve the address of a and b 52193248 >>> ia(b) 11616896960 por dab 4 £) output displayed pod 12 >>> b 12 >>> iaca) 1616896960 5 = Fe = = fe = Fs = = & yor stb) 5890300 Eeaneietirg 19) Sh tee ; Zaealonngvoten ote ee oie LLotel Lofied oF on > 4 5) Swap the values >>> b _ to a 2. What is the difference between a keyword and 2 variable? hat has a special meaning and Purpose. if, elif, else, etc., are keywords. vven to a value Variables are not fxed/reserved. These re definety digits and a symbol underscore. They must begin with either a ler vesult_1, etc, are the variable names in Python. ‘Ans. Keyword is a special wordt! Keywords are reserved and 2re fay For example, int, float, for, Variable is the user-defined name ‘the user but they can have letters, or underscore, For example, _age, name, 3. What is a function? How is it useful? ‘Ans. A function in Python is a named block of statements within 2 has a function within it, namely greet_™s 0. # progl-py def greet_msg (): print ("Hello there Pine = input( “Your name :” ) printiname, greet_msg ()) Functions are useful as they can be reused anywhere tl same functionality, one need not rewrite the code every time it is nee can be used again and again. 4, Find the error. def minus (total, decrement) output = total - decrement return output ‘Ans, The function’s header has colon missing at Thus, the corrected code will be: def minus (total, decrement): output = total - decrement return output 5. How many types of strings are supported in Python? ‘Ans. Python allows two string types: {1) Single line Strings—Strings that are terminated in single line. (2) Multiline Strings—Strings storing multiple lines of text. 6. What are variable-naming conventions? ‘Ans. () Avariable must start with a letter or underscore followed by any number of digits and/or lett a No reserved word or standard should be used as the variable name. i (ii) No special character (other than undersc it t ‘i (iv) Case sensitivity should be taken care e eo tei enced program. For example, following progre= ny hrough their function call statements. So, forthe .eded, rather through functions it 2) at the end of header line, t the end. So, we need to add colon Bj Zz i Es Fa = 8 A s 5 6 i ji yi Pi What is None in Python? Ans. Sython has one special type called None. The None ne s used to ind 1, unidentified value od.tt is anon-nu! cate someths & Keeniy the types of following literals: S. What is the difference between SSI and 55? Ans. An lor Lsuffix indicates it is long integer constant. Thus SSLis a long integer value and 5S is an integer value. 10. Find output genersted by the following code: fans. 5 3) (ans. 10 -8) (ans. 20 300) (Ans. 60 450) 5-642 (ans. 1.7599999999999998 62.5) 4.96 0.512) (ans. 27 11. What is the difference between an expression and a statement in Python? toe aor oe satement | 7. An expression is 2 combination of symbols, Statement is defined as any programming ‘operators and operands. instruction given in Python as per the syntax. 2. ‘An expression represents some value. Statement is given to execute a task. 3. The outcome of an expression is alwaysa value. Statement may or may not return a value as the result. oa jue ro ineinpe eater NUDE T) J Maem 1 5. identity i +2 result = mum ; F Group, i ru vert it into Fahrenheit using forms J mais B caeperatare in catsur and ome® \ pene sa wete 2 progam to obtal 1 Facsis32 ae sprenhe ‘ mire in Fahreneit is 37, #) i cece 0? ‘as. Ostpt shoud be ens, you are 21 now but you wil be 22 next yea. 16. What wil be the output of following code? n ¥=2,6 o nw int (9) Bal ans 64 Expanation,Festline of code assigns values 2 and 6 to variables x andy respectively Next line (second ine) of code fist evaluates right-hand side, Le, , x + 2, which is 6, 2+ 2, i., 6.4 And then assigns this 0% 1,% 9 =6, 43 s0.xgets 6 and y gets 4 5,2 +2, Le 6 Third line prints x and y 5 the output is 6 4, UNSOLVED ees 1. Write Python command/in 2. write Python command to 2. Evaluate the folowing expre fy @o3)er3-6/2 2439") (i 1248" *4- 0/2 (W) 12738542 4. Evaluate the above expressions by using IDL 5. Identify invalid variable names Group, i, int, total marks, 51, volume, tot st 6: Find the output of the following code: ) 4 peqte gtr rate print (Pdr) +. write Python expressions equivalent to the following arithmetic algebraic expressions e a Fs @ Fr — vor @) wstet (u, a, tare variables) Si Computer Science Se &. Write Python exrressions to represent the following stations: fa) Add remainder of 8/3 tp the product of 3 and 3. (2) Find the square rost of the sum of B and £3. {@) Find the sum of the souare conts of 8 and £3. (2) Find the integra! pant of the ouotient when 190 is divided by 22. &. What are operators? What is their function? Give examples of some unary gerd in 20. What is an expression and 2 statement? eats 2L What all components can 3 Python program contain? 412. What are variables? How ere they important for 2 program? 13, What is Dynamic Typing feature in Python? 18, Wite 2 function called celculate_area() thet takes bese and heigit 2s.an input e-gumens, area of 3 triangle 2s an output. The formula used is, ri Triangle Ares = M"base*height 15. Modify above function to take @ third parameter calied shape type Shape twos stolid ve ete ig cor rectangle. Sased on the shape should caleulate area. Formule used, Recangtc ree = eng 16, Write 2 function called print_patter that takes integer aumber 25 argument anc ors she = patter if the input number is 3. Mie Hf input is 4, then it should print, |. Write a function thet takes amount-in-dollars and dollar-to-rupee conversion price; ft then cour te ‘zmount converted to rupees. 18. What would the following code do? =b=70 19. What is the error in following code? zpos 20. Find out the error(s) in following code fragments? (i) temperature = 90 Print temperature (2) 2= 20 baatb print (2 And b) (3) a, by C= 2, 8, 9 print (a, by ©) c, bp ata,b,c print (a7 7 ¢) (4) x= 24 4=% (5) Brant CZ") | 2. 2a, 25. What will be the output produced by following code fragment(s)? () x= 10 X=x+10 X=x-5 print (x) X, Y"X- 2, 22 print (x, Y) (2) first =2 second = 3 third = first * second print (first, second, third) third = second * first print (first, second, third) (3) side = int (input (‘side’) #side given as 7 area = side * side print (side, area) “Comments are useful and an easy way to enhance readability and understand ability of a program.” Elaborate with examples. What is the problem with the foll ()a=3 print (a) b-4 print (b) s=atb print (5) (2) Name = “Prateek” Age = 26 ing code fragments? Print (“your name & age are”, Name + Age) @)aA=3 S=A+10 A= "New" o=A/10 Predict the output. x= 40 3 yextl x= 20, y+x print (x,y) Predict the output. x, y= 20,60 yr) Y= %, ¥~ 10, x +10 print (x, y) & Bs = Python| Program 26. Predict the output. y a, be 12, 13 : c, be at2, a/2 print (a, by ¢) 27, Predict the output. a,b, ¢ +10, 20, 30 Pg rec-5,at3,b-4 print (‘aandb, :!, py qr) ind errors in the following code fragment: (The input entered as X!) c= int (input (“Enter your class”) print (“Your class is”, c) 29, Find the errors in the following code fragment: cl= input (“Enter your class”) print ("Last year you were in class” cl-1) 30, Write a Python program that accepts radius of a circle and prints its area. 31, Write Python program that accepts marks in 5 subjects and outputs average marks, 28. 32. Write a program to find area of a triangle. 33, Write a program to input a number and print it 34, Write a program to read details ike name, class, age ofa student and then print the detallsftstlyinsa line and then in separate lines. ae) 35. Write a program to read three numbers in three variables and swap first two variables with the suns first and second, second and third numbers respectively. first five multiples. a Fi FS S ( r= 5 a 5 a a rl a G 5 5 5 Gy

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy