12th_Computer-Science_EM - www.tntextbooks.in.pdf

Document Details

DarlingDirac

Uploaded by DarlingDirac

2022

Tamil Nadu State Council of Educational Research and Training

Tags

computer science python programming

Full Transcript

www.tntextbooks.in GOVERNMENT OF TAMILNADU HIGHER SECONDARY SECOND YEAR...

www.tntextbooks.in GOVERNMENT OF TAMILNADU HIGHER SECONDARY SECOND YEAR COMPUTER SCIENCE A publication under Free Textbook Programme of Government of Tamil Nadu Department of School Education Untouchability is Inhuman and a Crime 12th Std - CS EM Introduction Pages.indd 1 30-12-2021 23:13:36 www.tntextbooks.in Government of Tamil Nadu First Edition - 2019 Revised Edition - 2020, 2022 (Published under New syllabus) NOT FOR SALE Content Creation The wise possess all State Council of Educational Research and Training © SCERT 2019 Printing & Publishing Tamil NaduTextbook and Educational Services Corporation www.textbooksonline.tn.nic.in II 12th Std - CS EM Introduction Pages.indd 2 30-12-2021 23:13:36 www.tntextbooks.in The tremendous effect of the computer and computing technology is in shaping the modern society for the betterment of mankind. Human civilization achieved the highest peak with the development of computer known as “Internet Era”. PREFACE Python being a high level language is good for beginners to learn due to its easy syntax and powerful memory management. For any internet applications, it is good to learn as python being the better choice. The user of this textbook being acquainted with the knowledge of C++ in std XI will have no difficulty in studying python language. No substantial knowledge nor experience, is required as the examples illustrated in the book are easy to follow HOW This book does not require TO USE prior knowledge in computer Technology THE BOOK?  ach unit comprises of simple E activities and demonstrations which can be done by the teacher and also students. Technical terminologies are listed in glossary for easy understanding  he “ Do you know?” boxes enrich the knowledge of reader with T additional information  orkshops are introduced to solve the exercises using software W applications QR codes are used to link supporting additional materials in digital form How to get connected to QR Code? o  Download the QR code scanner from the google play store/ apple app store into your smartphone o Open the QR code scanner application o Once the scanner button in the application is clicked, camera opens and then bring it closer to the QR code in the textbook. o Once the camera detects the QR code, a URL appears in the screen. Click the URL and go to the content page. III 12th Std - CS EM Introduction Pages.indd 3 30-12-2021 23:13:36 Computer Knowledge Hub C PG in Computer Science Centre ffor Development of Advanced Computing https://www.cdac.in/ Artificial Intelligence Database Management Indian Computing Olympiad https://www.iarcs.org.in/inoi Information Management Systems 12th Std - CS EM Introduction Pages.indd 4 International Olympiad of Informatics https://ioinformatics.org and Data Analytics Fundamentals of Algorithms Microsoft certification exams https://www.microsoft.com/en-in/learning/exam-list.aspx Algorithms Graphics National Cyber Olympiad http://www.sofworld.org/nco Applied Computer Science Machine Learning Big Data Analytics Mobile and Web Computing National Institute of Electronics & Information Technology http://www.nielit.gov.in/ Bio Informatics Mobile Device Programming National Programme on Technology Enhanced Learning https://nptel.ac.in/ Cloud Computing Modern Programming Practices Compiler Design & Modern Web Applications Construction Operating Systems After Completing +2 A Computer and Network Parallel Programming Security Robotics Scie Arts & Science BSc Courses | Animation & Multimedia Computer Networks Software Engineering Computer Science | Geography Computer Security Software Engineering Journalism / Mass Media Communication | Library Science Computer Simulation Software Testing Maths / Physics / Chemistry / Statistics | Psychology/ Sociology Cyber Security Systems Analysis and Design Social Work | Visual Communication | B.C.A. COMPUTER Data Analytics Web Application Architecture SCIENCE Data Mining Web Application Programming IV Technical Diploma Scholarships for graduate Diploma in Engineering D and post graduate courses www.tntextbooks.in DST – INSPIRE IN Fellowships (for Ph.D) Professional Degree & Entrance Exams P DST – INSPIRE Scholarships (for UG and PG) Hotel & Catering Institute http://www.ihmchennai.org/ihmchennai/ JEE-Joint Entrance Examination https://jeemain.nic.in/ In addition various fellowships for AIEEE- All India Engineering Entrance Exam JEST- Joint Entrance Screening Test https://www.jest.org.in SC/ST/PWD, B.E/B.Tech/ B.Arch (JEE, AIEEE in IITs and NITs) Law 5-Year Integrated Course http://tndalu.ac.in Indira Gandhi Fellowship for Fashion Technology & Design http://nift.ac.in National Defence Academy https://www.nda.nic.in Single girl child (for UG and PG) GATE-Graduate Aptitude Test in Engineering NET- National Eligibility Test (CSIR and UGC) http://cbsenet.nic.in Moulana Azad Fellowship www gate.iitm.ac.in TamilNadu Dr. Ambedkar Law University http://tndalu.ac.in for minorities (for Ph.D) Indian Navy – 10+2 BTech Entry Scheme Technical Entry Scheme – Army/Navy/Airforce UGC National Fellowship (for Ph.D) CAREER GUIDANCE AFTER 12TH Institute of Chartered Accountants of India https://icai.org TIFR GS - Tata Institute of Fundamental International Olympiad: for getting stipend for Institute of Company Secretary https://www.icsi.edu Research Graduate School http://univ.tifr.res.in Higher Education in Science and Mathematics Institute of Cost Accountants of India http://icmai.in Visual Arts Degree OBC etc are available. Institute of Banking Personal Selection IBPS https://ibps.in http://www.tndipr.gov.in/television-traininginstitute.aspx Visit website of University Grants Commission 30-12-2021 23:13:36 After PG courses A Competitive Exams for Govt. Jobs MPhil –Computer Science | PhD – Computer Science Airforce Common Admission Test – AFCAT | Army Education Officer Entry- AEC Combined Defence Services –CDS | Defence Service Staff College, Nilgiris Following are the latest topics for PhD in computer science: 12th Std - CS EM Introduction Pages.indd 5 Indian Defence Services | Indian Military Academy BioInformatics and Computational Biology Judge Advocate General Department-JAG | NCC Entry | Railway Board Examination Capturing and Visualizing Persona Through Faces SSC NAVY (Pilot/Observer) | SSC Tech Entry – Officers Training School Comprehensive analysis of RNA sequencing experiments Staff Selection Examination | Tamil Nadu Public Service Commission Designing and Evaluating Information Gathering Robots Teacher Recruitment Board | Technical Graduate Course –TGC Digital Pathology: Diagnostic Errors, Territorial Army | Union Public Service Examination | Women Special Entry Scheme Viewing Behavior and Image Characteristics Embedded Systems | Game Theory | Graph Theory Graphics and Visualization | Human Computer Interaction – HCI Computer Related Jobs Improving Fault Tolerance and Performance of Data Center Networks Increasing Access to Computer Science for Blind Students Applications Software Developer | Big Data Analysts In-situ Semantic 3D Modeling Cloud Computing Programmer | College/ University Faculty Intelligent Crowdsourcing for Natural Language Computer Programmer | Computer Teacher Learning and Other AI Applications Computer Vocational Instructor | Computer Information Research Scientist Learning Robust Tractable Models for Vision COMPUTER Computer Information Systems Manager | Computer Network Architect Govt V SCIENCE Computer Support Specialist | Computer System Analysts Manipulators And Manipulation In High Dimensional Spaces Data Mining Specialist | Database Administrator New Algorithmic Tools for Distributed Similarity Search Information Security Analysts | Market Research Analysts Reproducible measurements of web security and privacy Network & Computer System Administrator | Research Assistant www.tntextbooks.in The Security and Privacy of Web and Mobile Advertising Systems Software Developer | User Interface Designer | Web Developer Towards More Practical Reinforcement Learning, with Applications to Educational Games Research Institutions in various areas of science Bhaba Atomic Research centre Institute of Mathematical Sciences (IMSc) (BARC) Mumbai www.barc.gov.in Chennai www.imsc.res.in CAREER GUIDANCE BITS Pilani, https://www.bits-pilani.ac.in Jawaharlal Nehru University (JNU) www.jnu.ac.in Topics for Research after PG in Computer Studies T Central Universities www.ugc.ac.in Mumbai University, Mumbai www.mu.ac.in Chennai Mathematical Institute National Institute of Science Education and Architectures, Compiler Optimization, and Embedded Systems. (CMI) Chennai www.cmi.ac.in Research (NISER), www.niser.ac.in Bioinformatics and Computational Biology | Cloud Computing Delhi University, Delhi www.du.ac.in National Institute of Technology Hyderabad central university, (NITs) www.nitt.edu Data Mining, Databases, and Geographical Information Systems. Hyderabad www.uohyd.ac.in SavithiribaiPhule Pune university, Graphics and Visualization | High Performance Computing. Pune www.unipune.ac.in IISER Educational Institutions Human Computer Interaction | Internet of Things www.iiseradmission.in State Universities https://www.ugc.ac.in Natural Language Processing | Networks, Distributed Systems, and Security. Indian Institute of Technology in Tata Institute of Fundamental Research various places (IIT’s) www.iitm.ac.in (TIFR) Mumbai www.tifr.res.in 30-12-2021 23:13:37 www.tntextbooks.in Table of Contents Computer Science-II Year UNIT NO. CHAPTER COMPUTER SCIENCE PAGE NO MONTH UNIT- I 1 Function 1 June Problem 2 Data Abstraction 11 June Solving 3 Scoping 21 June Techniques 4 Algorithmic Strategies 31 June 5 Python -Variables and Operators 47 July UNIT- II 6 Control Structures 67 July Core Python 7 Python functions 89 July 8 Strings and String manipulation 114 Aug UNIT-III 9 Lists, Tuples, Sets and Dictionary 132 Aug Modularity and OOPS 10 Python Classes and objects 170 Aug UNIT-IV 11 Database Concepts 189 Oct Database 12 Structured Query Language (SQL) 205 Oct concepts and MySql 13 Python and CSV files 232 Oct Importing C++ programs in 14 267 Oct UNIT-V Python. Integrating 15 Data manipulation through SQL 291 Nov Python with MySql and C++ Data visualization using pyplot: line 16 320 Nov chart, pie chart and bar chart Glossary 335 Annexure-1 List of Python functions 341 Installation of MySQL and Creating a Annexure-2 345 Database Annexure-3 Installation of MinGW 346 Annexure-4 Installation of pip 351 E - book Assessment VI 12th Std - CS EM Introduction Pages.indd 6 30-12-2021 23:13:37 www.tntextbooks.in CHAPTER 1 Unit I FUNCTION 1.2 Function with respect to Learning Objectives Programming language After the completion of this chapter, the A function is a unit of code that is student will be able to: often defined within a greater code structure. Specifically, a function contains a set of Understand Function Specification. code that works on many kinds of inputs, Parameters (and arguments). like variants, expressions and produces a Interface Vs Implementation. concrete output. Pure functions. 1.2.1 Function Specification Side - effects (impure functions). Let us consider the example a:= (24). a:= (24) has an expression in it but (24) 1.1 Introduction is not itself an expression. Rather, it is a The most important criteria in function definition. Definitions bind values writing and evaluating the algorithm is the to names, in this case the value 24 being time it takes to complete a task. To have bound to the name ‘a’. Definitions are not a meaningful comparison of algorithms, expressions, at the same time expressions are the duration of computation time must be also not treated as definitions. Definitions independent of the programming language, are distinct syntactic blocks. Definitions can compiler, and computer used. As you have expressions nested inside them, and aware that algorithms are expressed using vice-versa. statements of a programming language. If a 1.2.2 Parameters (and arguments) bulk of statements to be repeated for many numbers of times then subroutines are used Parameters are the variables in a to finish the task. function definition and arguments are the values which are passed to a function Subroutines are the basic building definition. blocks of computer programs. Subroutines 1. Parameter without Type are small sections of code that are used to perform a particular task that can be used Let us see an example of a function repeatedly. In Programming languages these definition: subroutines are called as Functions. 1 12th Computer Science_EM Chapter 1.indd 1 22-12-2021 14:49:33 www.tntextbooks.in for ‘a’ and ‘b’ the parentheses are (requires: b>=0 ) mandatory. Generally we can leave out (returns: a to the power of b) these annotations, because it's simpler to let rec pow a b:= let the compiler infer them. There are times if b=0 then 1 we may want to explicitly write down types. else a * pow a (b-1) This is useful on times when you get a type error from the compiler that doesn't make sense. Explicitly annotating the types can In the above function definition help with debugging such an error message. variable ‘b’ is the parameter and the value which is passed to the variable ‘b’ is the The syntax to define functions is close argument. The precondition (requires) and to the mathematical usage: the definition is postcondition (returns) of the function introduced by the keyword let, followed by is given. Note we have not mentioned any the name of the function and its arguments; types: (data types). Some language compiler then the formula that computes the image solves this type (data type) inference of the argument is written after an := sign. If problem algorithmically, but some require you want to define a recursive function: use the type to be mentioned. “let rec” instead of “let”. In the above function definition if Syntax: The syntax for function definitions: expression can return 1 in the then branch, shows that as per the typing rule the entire if expression has type int. Since the let rec fn a1 a2... an := k if expression is of type ‘int’, the function's return type also be ‘int’. ‘b’ is compared to Here the ‘fn’ is a variable indicating 0 with the equality operator, so ‘b’ is also an identifier being used as a function a type of ‘int’. Since ‘a’ is multiplied with name. The names ‘a1’ to ‘an’ are variables another expression using the * operator, ‘a’ indicating the identifiers used as parameters. must be an int. The keyword ‘rec’ is required if ‘fn’ is to be a recursive function; otherwise it may be 2. Parameter with Type omitted. Now let us write the same function definition with types for some reason: Note (requires: b>=0 ) A function definition which call itself is called recursive function. (returns: a to the power of b ) let rec pow (a: int) (b: int) : int := For example: let us see an example to check if b=0 then 1 whether the entered number is even or odd. else a * pow a (b-1) When we write the type annotations XII Std Computer Science 2 12th Computer Science_EM Chapter 1.indd 2 22-12-2021 14:49:33 www.tntextbooks.in interface. In our example, anything that (requires: x>= 0) let rec even x := "ACTS LIKE" a light, should have function x=0 || odd (x-1) definitions like turn_on () and a turn_off return ‘even’ (). The purpose of interface is to allow the (requires: x>= 0) computer to enforce the properties of the let odd x := class of TYPE T (whatever the interface is) x0 && even (x-1) must have functions called X, Y, Z, etc. return ‘odd’ A class declaration combines the The syntax for function types: external interface (its local state) with an implementation of that interface (the code x→y that carries out the behaviour). An object is x1 → x2 → y an instance created from the class. x1 →... → xn → y The interface defines an object’s visibility to the outside world. The ‘x’ and ‘y’ are variables indicating types. The type x → y is the type of a function The difference between interface and that gets an input of type ‘x’ and returns an implementation is output of type ‘y’. Whereas x1 → x2 → y is a type of a function that takes two inputs, Interface Implementation the first input is of type ‘x1’ and the second input of type ‘x2’, and returns an output of Interface just Implementation type ‘y’. Likewise x1 → … → xn → y has defines what carries out the type ‘x’ as input of n arguments and ‘y’ type an object can instructions defined do, but won’t in the interface as output. actually do it Note In object oriented programs classes are All functions are static the interface and how the object is processed definitions. There is no dynamic and executed is the implementation. function definitions. 1.3.1 Characteristics of interface The class template specifies the interfaces 1.3 Interface Vs Implementation to enable an object to be created and An interface is a set of action that an operated properly. object can do. For example when you press a light switch, the light goes on, you may An object's attributes and behaviour is not have cared how it splashed the light. In controlled by sending functions to the Object Oriented Programming language, object. an Interface is a description of all functions that a class must have in order to be a new For example, let's take the example of increasing a car’s speed. 3 Function 12th Computer Science_EM Chapter 1.indd 3 22-12-2021 14:49:33 www.tntextbooks.in let min 3 x y z := ENGINE if x < y then if x < z then x else z else if y < z then y else z getSpeed 1.4 Pure functions required No Pure functions are functions which Pull Fuel speed will give exact result when the same arguments are passed. For example the Yes mathematical function sin (0) always results Return 0. This means that every time you call the function with the same arguments, you will always get the same result. A function can The person who drives the car be a pure function provided it should not doesn't care about the internal working. To have any external variable which will alter increase the speed of the car he just presses the behaviour of that variable. the accelerator to get the desired behaviour. Here the accelerator is the interface between Let us see an example the driver (the calling / invoking object) and the engine (the called object). let square x In this case, the function call would return: x * x be Speed (70): This is the interface. Internally, the engine of the car is The above function square is a pure doing all the things. It's where fuel, air, function because it will not give different pressure, and electricity come together to results for same input. create the power to move the vehicle. All of There are various theoretical these actions are separated from the driver, advantages of having pure functions. One who just wants to go faster. Thus we separate advantage is that if a function is pure, then interface from implementation. if it is called several times with the same Let us see a simple example, consider arguments, the compiler only needs to the following implementation of a function actually call the function once. Lt’s see an that finds the minimum of its three example arguments: let length s:= i: = 0 if i >>) whereas in script mode programs can be written and stored as separate file with the extension.py and executed. Script mode is used to create and edit python source file. 5.3.1 Interactive mode Programming In interactive mode Python code can be directly typed and the interpreter displays the result(s) immediately. The interactive mode can also be used as a simple calculator. (i) Invoking Python IDLE The following command can be used to invoke Python IDLE from Window OS. Start → All Programs → Python 3.x → IDLE (Python 3.x) (Or) Click python Icon on the Desktop if available. Now Python IDLE window appears as shown in the Figure 5.1 Menu Bar Tilte Bar Python prompt (>>>) Python IDLE Window The prompt (>>>) indicates that Interpreter is ready to accept instructions. Therefore, the prompt on screen means IDLE is working in interactive mode. Now let us try as a simple calculator by using a simple mathematical expressions. XII Std Computer Science 48 12th Computer Science_EM Chapter 5.indd 48 22-12-2021 15:09:36 www.tntextbooks.in Example 1: Example 2: >>> 5 + 10 >>>print (“Python Programming Language”) 15 Python Programming Language >>>x=10 >>> 5 + 50 *10 >>>y=20 505 >>>z=x + y >>> 5 ** 2 >>>print (“The Sum”, z) 25 The Sum = 30 Python Interactive Window 5.3.2 Script mode Programming Basically, a script is a text file containing the Python statements. Python Scripts are reusable code. Once the script is created, it can be executed again and again without retyping. The Scripts are editable. (i) Creating Scripts in Python 1. Choose File → New File or press Ctrl + N in Python shell window. 49 Python – Variables and Operators 12th Computer Science_EM Chapter 5.indd 49 22-12-2021 15:09:36 www.tntextbooks.in Figure 5.3 – To create new File 2. An untitled blank script text editor will be displayed on screen as shown in Figure 5.3(a) Figure 5.3(a) Untitled, blank Python script editor 3. Type the following code in Script editor a =100 b = 350 a = 100 b = 350 c = a+b c = a+b print ("The Sum=", c) print ("The Sum=", c) Figure 5.4 – Python Sample code XII Std Computer Science 50 12th Computer Science_EM Chapter 5.indd 50 22-12-2021 15:09:36 www.tntextbooks.in (ii) Saving Python Script (1) Choose File → Save or Press Ctrl + S Figure 5.5 – To Save the file First time (2) Now, Save As dialog box appears on the screen as shown in the Figure 5.6 File Location File Name (demo1) File Type (Python file (.py)) Figure 5.6 – Save As Dialog Box 51 Python – Variables and Operators 12th Computer Science_EM Chapter 5.indd 51 22-12-2021 15:09:37 www.tntextbooks.in (3) In the Save As dialog box, select the location where you want to save your Python code, and type the file name in File Name box. Python files are by default saved with extension.py. Thus, while creating Python scripts using Python Script editor, no need to specify the file extension. (4) Finally, click Save button to save your Python script. (iii) Executing Python Script (1) Choose Run → Run Module or Press F5 a=100 b=350 c=a+b print ("The Sum=", c) Figure 5.7 – To Execute Python Script (2) If your code has any error, it will be shown in red color in the IDLE window, and Python describes the type of error occurred. To correct the errors, go back to Script editor, make corrections, save the file using Ctrl + S or File → Save and execute it again. (3) For all error free code, the output will appear in the IDLE window of Python as shown in Figure 5.8 Output Figure 5.8 –Python Script Output Window XII Std Computer Science 52 12th Computer Science_EM Chapter 5.indd 52 22-12-2021 15:09:37 www.tntextbooks.in 5.4 Input and Output Functions A program needs to interact with the user to accomplish the desired task; this can be achieved using Input-Output functions. The input() function helps to enter data at run time by the user and the output function print() is used to display the result of the program on the screen after execution. 5.4.1 The print() function In Python, the print() function is used to display result on the screen. The syntax for print() is as follows: Example print (“string to be displayed as output ” ) print (variable ) print (“String to be displayed as output ”, variable) print (“String1 ”, variable, “String 2”, variable, “String 3” ……) Example >>> print (“Welcome to Python Programming”) Welcome to Python Programming >>> x = 5 >>> y = 6 >>> z = x + y >>> print (z) 11 >>> print (“The sum = ”, z) The sum = 11 >>> print (“The sum of ”, x, “ and ”, y, “ is ”, z) The sum of 5 and 6 is 11 The print ( ) evaluates the expression before printing it on the monitor. The print () displays an entire statement which is specified within print ( ). Comma ( , ) is used as a separator in print ( ) to print more than one item. 5.4.2 input() function In Python, input( ) function is used to accept data as input at run time. The syntax for input() function is, Variable = input (“prompt string”) 53 Python – Variables and Operators 12th Computer Science_EM Chapter 5.indd 53 22-12-2021 15:09:37 www.tntextbooks.in Where, prompt string in the syntax is a statement or message to the user, to know what input can be given. If a prompt string is used, it is displayed on the monitor; the user can provide expected data from the input device. The input( ) takes whatever is typed from the keyboard and stores the entered data in the given variable. If prompt string is not given in input( ) no message is displayed on the screen, thus, the user will not know what is to be typed as input. Example 1:input( ) with prompt string >>> city=input (“Enter Your City: ”) Enter Your City: Madurai >>> print (“I am from “, city) I am from Madurai Example 2:input( ) without prompt string >>> city=input() Rajarajan >>> print (“I am from”, city) I am from Rajarajan Note that in example-2, the input( ) is not having any prompt string, thus the user will not know what is to be typed as input. If the user inputs irrelevant data as given in the above example, then the output will be unexpected. So, to make your program more interactive, provide prompt string with input( ). The input ( ) accepts all data as string or characters but not as numbers. If a numerical value is entered, the input values should be explicitly converted into numeric data type. The int( ) function is used to convert string data as integer data explicitly. We will learn about more such functions in later chapters. Example 3: x = int (input(“Enter Number 1: ”)) y = int (input(“Enter Number 2: ”)) print (“The sum = ”, x+y) Output: Enter Number 1: 34 Enter Number 2: 56 The sum = 90 XII Std Computer Science 54 12th Computer Science_EM Chapter 5.indd 54 22-12-2021 15:09:37 www.tntextbooks.in Example 4: Alternate method for the above program x,y=int (input("Enter Number 1 :")),int(input("Enter Number 2:")) print ("X = ",x," Y = ",y) Output: Enter Number 1 :30 Enter Number 2:50 X = 30 Y = 50 5.5 Comments in Python In Python, comments begin with hash symbol (#). The lines that begins with # are considered as comments and ignored by the Python interpreter. Comments may be single line or no multi-lines. The multiline comments should be enclosed within a set of ''' '''(triple quotes) as given below. # It is Single line Comment ''' It is multiline comment which contains more than one line ''' 5.6 Indentation Python uses whitespace such as spaces and tabs to define program blocks whereas other languages like C, C++, java use curly braces { } to indicate blocks of codes for class, functions or body of the loops and block of selection command. The number of whitespaces (spaces and tabs) in the indentation is not fixed, but all statements within the block must be indented with same amount spaces. 5.7 Tokens Python breaks each logical line into a sequence of elementary lexical components known as Tokens. The normal token types are 1) Identifiers, 2) Keywords, 3) Operators, 4) Delimiters and 5) Literals. Whitespace separation is necessary between tokens, identifiers or keywords. 5.7.1. Identifiers An Identifier is a name used to identify a variable, function, class, module or object. 55 Python – Variables and Operators 12th Computer Science_EM Chapter 5.indd 55 22-12-2021 15:09:37 www.tntextbooks.in An identifier must start with an alphabet (A..Z or a..z) or underscore ( _ ). Identifiers may contain digits (0.. 9) Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct. Identifiers must not be a python keyword. Python does not allow punctuation character such as %,$, @ etc., within identifiers. Example of valid identifiers Sum, total_marks, regno, num1 Example of invalid identifiers 12Name, name$, total-mark, continue 5.7.2. Keywords Keywords are special words used by Python interpreter to recognize the structure of program. As these words have specific meaning for interpreter, they cannot be used for any other purpose. Table 5.1 Python’s Keywords False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if or yield assert else import pass break except in raise 5.7.3 Operators In computer programming languages operators are special symbols which represent computations, conditional matching etc. The value of an operator used is called operands. Operators are categorized as Arithmetic, Relational, Logical, Assignment etc. Value and variables when used with operator are known as operands. (i) Arithmetic operators An arithmetic operator is a mathematical operator that takes two operands and performs a calculation on them. They are used for simple arithmetic. Most computer languages contain a set of such operators that can be used within equations to perform different types of sequential calculations. XII Std Computer Science 56 12th Computer Science_EM Chapter 5.indd 56 22-12-2021 15:09:37 www.tntextbooks.in Python supports the following Arithmetic operators. Operator - Operation Examples Result Assume a=100 and b=10. Evaluate the following expressions + (Addition) >>> a + b 110 - (Subtraction) >>>a – b 90 * (Multiplication) >>> a*b 1000 / (Divisioin) >>> a / b 10.0 % (Modulus) >>> a % 30 10 ** (Exponent) >>> a ** 2 10000 // (Floor Division) >>> a//30 (Integer Division) 3 Program 5.1 To test Arithmetic Operators: #Demo Program to test Arithmetic Operators a=100 b=10 print ("The Sum = ",a+b) print ("The Difference = ",a-b) print ("The Product = ",a*b) print ("The Quotient = ",a/b) print ("The Remainder = ",a%30) print ("The Exponent = ",a**2) print ("The Floor Division =",a//30) #Program End Output: The Sum = 110 The Difference = 90 The Product = 1000 The Quotient = 10.0 The Remainder = 10 The Exponent = 10000 The Floor Division = 3 (ii) Relational or Comparative operators A Relational operator is also called as Comparative operator which checks the relationship between two operands. If the relation is true, it returns True; otherwise it returns False. 57 Python – Variables and Operators 12th Computer Science_EM Chapter 5.indd 57 22-12-2021 15:09:37 www.tntextbooks.in Python supports following relational operators Operator - Operation Examples Result Assume the value of a=100 and b=35. Evaluate the following expressions. == (is Equal) >>> a==b False > (Greater than) >>> a > b True < (Less than) >>> a < b False >= (Greater than or Equal to) >>> a >= b True >> a >> a != b True Coding 5.2 To test Relational Operators: #Demo Program to test Relational Operators a=int (input("Enter a Value for A:")) b=int (input("Enter a Value for B:")) print ("A = ",a," and B = ",b) print ("The a==b = ",a==b) print ("The a > b = ",a>b) print ("The a < b = ",a=b) print ("The a b or a == b = ",a>b or a==b) The a > b and a == b = False print ("The a > b and a == b = ",a>b and a==b) The not a > b = False print ("The not a > b = ",not a>b) #Program End (iv) Assignment operators In Python, = is a simple assignment operator to assign values to variable. Let a = 5 and b = 10 assigns the value 5 to a and 10 to b these two assignment statement can also be given as a,b=5,10 that assigns the value 5 and 10 on the right to the variables a and b respectively. There are various compound operators in Python like +=, -=, *=, /=, %=, **= and //= are also available. Operator Description Example Assume x=10 >>> x=10 = Assigns right side operands to left variable >>> b=”Computer” Added and assign back the result += >>> x+=20 # x=x+20 to left operand i.e. x=30 Subtracted and assign back the -= >>> x-=5 # x=x-5 result to left operand i.e. x=25 Multiplied and assign back the *= >>> x*=5 # x=x*5 result to left operand i.e. x=125 Divided and assign back the /= >>> x/=2 # x=x/2 result to left operand i.e. x=62.5 59 Python – Variables and Operators 12th Computer Science_EM Chapter 5.indd 59 22-12-2021 15:09:37 www.tntextbooks.in Taken modulus(Remainder) using two %= operands and assign the result >>> x%=3 # x=x%3 to left operand i.e. x=2.5 Performed exponential (power) calculation on **= operators and assign value to the left operand >>> x**=2 # x=x**2 i.e. x=6.25 Performed floor division on operators and //= >>> x//=3 assign value to the left operand i.e. x=2.0 Program 5.4 To test Assignment Operators: Program Coding Output #Demo Program to test Assignment Operators Type a Value for X : 10 x=int (input("Type a Value for X : ")) X = 10 print ("X = ",x) The x is = 10 print ("The x is =",x) The x += 20 is = 30 x+=20 The x -= 5 is = 25 print ("The x += 20 is =",x) The x *= 5 is = 125 x-=5 The x /= 2 is = 62.5 print ("The x -= 5 is = ",x) The x %= 3 is = 2.5 x*=5 The x **= 2 is = 6.25 print ("The x *= 5 is = ",x) The x //= 3 is = 2.0 x/=2 print ("The x /= 2 is = ",x) x%=3 print ("The x %= 3 is = ",x) x**=2 print ("The x **= 2 is = ",x) x//=3 print ("The x //= 3 is = ",x) #Program End (v) Conditional operator Ternary operator is also known as conditional operator that evaluate something based on a condition being true or false. It simply allows testing a condition in a single line replacing the multiline if-else making the code compact. XII Std Computer Science 60 12th Computer Science_EM Chapter 5.indd 60 22-12-2021 15:09:37 www.tntextbooks.in The Syntax conditional operator is, Variable Name = [on_true] if [Test expression] else [on_false] Example : min= 49 if 4950 else 49 # min = 49 Program 5.5 To test Conditional (Ternary) Operator: # Program to demonstrate conditional operator a, b = 30, 20 # Copy value of a in min if a < b else copy b min = a if a < b else b print ("The Minimum of A and B is ",min) # End of the Program Output: The Minimum of A and B is 20 5.7.4 Delimiters Python uses the symbols and symbol combinations as delimiters in expressions, lists, dictionaries and strings. Following are the delimiters. ( ) [ ] { } , :. ‘ = ; += -= *= /= //= %= &= |= ^= >>= >> print("\\test") \test \’ Single-quote >>> print("Doesn\'t") Doesn't \” Double-quote >>> print("\"Python\"") "Python" \n New line print("Python","\n","Lang..") Python Lang.. \t Tab print("Python","\t","Lang..") Python Lang.. 5.8 Python Data types All data values in Python are objects and each object or value has type. Python has Built-in or Fundamental data types such as Number, String, Boolean, tuples, lists, sets and dictionaries etc. 63 Python – Variables and Operators 12th Computer Science_EM Chapter 5.indd 63 22-12-2021 15:09:37 www.tntextbooks.in 5.8.1 Number Data type The built-in number objects in Python supports integers, floating point numbers and complex numbers. Integer Data can be decimal, octal or hexadecimal. Octal integer use digit 0 (Zero) followed by letter 'o' to denote octal digits and hexadecimal integer use 0X (Zero and either uppercase or lowercase X) and L (only upper case) to denote long integer. Example : 102, 4567, 567 # Decimal integers 0o102, 0o876, 0o432 # Octal integers 0X102, 0X876, 0X432 # Hexadecimal integers 34L, 523L # Long decimal integers A floating point data is represented by a sequence of decimal digits that includes a decimal point. An Exponent data contains decimal digit part, decimal point, exponent part followed by one or more digits. Example : 123.34, 456.23, 156.23 # Floating point data 12.E04, 24.e04 # Exponent data Complex number is made up of two floating point values, one each for the real and imaginary parts. 5.8.2 Boolean Data type A Boolean data can have any of the two values: True or False. Example : Bool_var1=True Bool_var2=False 5.8.3 String Data type String data can be enclosed in single quotes or double quotes or triple quotes. Example : Char_data = ‘A’ String_data= "Computer Science" Multiline_data= ”””String data can be enclosed in single quotes or double quotes or triple quotes.””” XII Std Computer Science 64 12th Computer Science_EM Chapter 5.indd 64 22-12-2021 15:09:37 www.tntextbooks.in Points to remember: Python is a general purpose programming language created by Guido Van Rossum. Python shell can be used in two ways, viz., Interactive mode and Script mode. Python uses whitespace (spaces and tabs) to define program blocks Whitespace separation is necessary between tokens, identifiers or keywords. A Program needs to interact with end user to accomplish the desired task, this is done using Input-Output facility. Python breaks each logical line into a sequence of elementary lexical components known as Tokens. Keywords are special words that are used by Python interpreter to recognize the structure of program. Evaluation Part - I Choose the best answer (1 Marks) 1. Who developed Python ? A) Ritche B) Guido Van Rossum C) Bill Gates D) Sunder Pitchai 2. The Python prompt indicates that Interpreter is ready to accept instruction. A) >>> B) > As you can see in the second execution no output will be printed, only the Python prompt will be displayed because the program does not check the alternative process when the condition is failed. (ii) if..else statement The if.. else statement provides control to check the true block as well as the false block. Following is the syntax of ‘if..else’ statement. Syntax: if : statements-block 1 else: statements-block 2 69 Control Structures XII Std - CS EM Chapter-6.indd 69 08-12-2021 18:56:34 www.tntextbooks.in Entry if condition is if condition is true condition false Statement Statement block -1 block -2 Exit Fig. 6.1 if..else statement execution if..else statement thus provides two possibilities and the condition determines which BLOCK is to be executed. Example 6.3: #Program to check if the accepted number odd or even a = int(input("Enter any number :")) if a%2==0: print (a, " is an even number") else: print (a, " is an odd number") Output 1: Enter any number :56 56 is an even number Output 2: Enter any number :67 67 is an odd number An alternate method to rewrite the above program is also available in Python. The complete if..else can also written as: Syntax: variable = variable1 if condition else variable 2 XII Std Computer Science 70 XII Std - CS EM Chapter-6.indd 70 08-12-2021 18:56:34 www.tntextbooks.in Note The condition specified in the if is checked, if it is true, the value of variable1 is stored in variable on the left side of the assignment, otherwise variable2 is taken as the value. Example 6.4: #Program to check if the accepted number is odd or even (using alternate method of if...else) a = int (input("Enter any number :")) x="even" if a%2==0 else "odd" print (a, " is ",x) Output 1: Enter any number :3 3 is odd Output 2: Enter any number :22 22 is even (iii) Nested if..elif...else statement: When we need to construct a chain of if statement(s) then ‘elif ’ clause can be used instead of ‘else’. Syntax: if : statements-block 1 elif : statements-block 2 else: statements-block n In the syntax of if..elif..else mentioned above, condition-1 is tested if it is true then statements-block1 is executed, otherwise the control checks condition-2, if it is true statements- block2 is executed and even if it fails statements-block n mentioned in else part is executed. 71 Control Structures XII Std - CS EM Chapter-6.indd 71 08-12-2021 18:56:34 www.tntextbooks.in Test false Expression of if True Test false Expression Body of if of elif True Body of else Body of elif Fig 6.2 if..elif..else statement execution ‘elif ’ clause combines if..else-if..else statements to one if..elif…else. ‘elif ’ can be considered to be abbreviation of ‘else if ’. In an ‘if ’ statement there is no limit of ‘elif ’ clause that can be used, but an ‘else’ clause if used should be placed at the end. Note if..elif..else statement is similar to nested if statement which you have learnt in C++. XII Std Computer Science 72 XII Std - CS EM Chapter-6.indd 72 08-12-2021 18:56:34 www.tntextbooks.in Example 6.5: #Program to illustrate the use of nested if statement Average Grade >=80 and above A >=70 and =60 and =50 and =80: print (“Grade : A”) elif avg>=70 and avg=60 and avg=50 and avg>> n1 = eval (input ("Enter a number: ")) Enter a number: 234 >>> n1 234 >>> n2 = eval (input ("Enter an arithmetic expression: ")) Enter an arithmetic expression: 12.0+13.0 * 2 >>> n2 38.0 7.10 Python recursive functions When a function calls itself is known as recursion. Recursion works like loop but sometimes it makes more sense to use recursion than loop. You can convert any loop to 107 Python Functions 12th Computer Science_EM Chapter 7.indd 107 22-12-2021 15:12:58 www.tntextbooks.in recursion. A recursive function calls itself. Imagine a process would iterate indefinitely if not stopped by some condition! Such a process is known as infinite iteration. The condition that is applied in any recursive function is known as base condition. A base condition is must in every recursive function otherwise it will continue to execute like an infinite loop. Overview of how recursive function works 1. Recursive function is called by some external code. 2. If the base condition is met then the program gives meaningful output and exits. 3. Otherwise, function does some required processing and then calls itself to continue recursion. Here is an example of recursive function used to calculate factorial. Example : def fact(n): if n == 0: return 1 else: return n * fact (n-1) print (fact (0)) print (fact (5)) Output: 1 120 print(fact (2000)) will give Runtime Error after maximum recursion depth exceeded in comparison. This happens because python stops calling recursive function after 1000 calls by default. It also allows you to change the limit using sys.setrecursionlimit (limit_value). Example: import sys sys.setrecursionlimit(3000) def fact(n): if n == 0: return 1 else: return n * fact(n-1) print(fact (2000)) XII Std Computer Science 108 12th Computer Science_EM Chapter 7.indd 108 22-12-2021 15:12:58 www.tntextbooks.in Points to remember: Functions are named blocks of code that are designed to do one specific job. Types of Functions are User defined, Built-in, lambda and recursion. Function blocks begin with the keyword “def ” followed by function name and parenthesis (). A “return” with no arguments is the same as return None. Return statement is optional in python. In Python, statements in a block should begin with indentation. A block within a block is called nested block. Arguments are used to call a function and there are primarily 4 types of functions that one can use: Required arguments, Keyword arguments, Default arguments and Variable-length arguments. Required arguments are the arguments passed to a function in correct positional order. Keyword arguments will invoke the function after the parameters are recognized by their parameter names. A Python function allows to give the default values for parameters in the function definition. We call it as Default argument. Variable-Length arguments are not specified in the function’s definition and an asterisk (*) is used to define such arguments. Anonymous Function is a function that is defined without a name. Scope of variable refers to the part of the program, where it is accessible, i.e., area where you can refer (use) it. The value returned by a function may be used as an argument for another function in a nested manner. This is called composition. A function which calls itself is known as recursion. Recursion works like a loop but sometimes it makes more sense to use recursion than loop. 109 Python Functions 12th Computer Science_EM Chapter 7.indd 109 22-12-2021 15:12:58 www.tntextbooks.in Hands on Experience 1. Try the following code in the above program Slno code Result 1 printinfo(“3500”) 2 printinfo(“3500”,”Sri”) 3 printinfo(name=”balu”) 4 printinfo(“Jose”,1234) 5 printinfo(“ ”,salary=1234) 2. Evaluate the following functions and write the output Slno Function Output 1 eval(‘25*2-5*4') 2 math.sqrt(abs(-81)) 3 math.ceil(3.5+4.6) 4 math.floor(3.5+4.6) 3. Evaluate the following functions and write the output Slno function Output 1 1) abs(-25+12.0)) 2) abs(-3.2) 2 1) ord('2') 2) ord('$') 3 type('s') 4 bin(16) 5 1) chr(13) 2) print(chr(13)) 6 1) round(18.2,1) 2) round(18.2,0) 3) round(0.5100,3) 4) round(0.5120,3) XII Std Computer Science 110 12th Computer Science_EM Chapter 7.indd 110 22-12-2021 15:12:58 www.tntextbooks.in 7 1) format(66, 'c') 2) format(10, 'x') 3) format(10, 'X') 4) format(0b110, 'd') 5) format(0xa, 'd') 8 1) pow(2,-3) 2) pow(2,3.0) 3) pow(2,0) 4) pow((1+2),2) 5) pow(-3,2) 6) pow(2*2,2) Evaluation Part - I Choose the best answer: (1 Mark) 1. A named blocks of code that are designed to do one specific job is called as (a) Loop (b) Branching (c) Function (d) Block 2. A Function which calls itself is called as (a) Built-in (b) Recursion (c) Lambda (d) return 3. Which function is called anonymous un-named function (a) Lambda (b) Recursion (c) Function (d) define 4. Which of the following keyword is used to begin the function block? (a) define (b) for (c) finally (d) def 5. Which of the following keyword is used to exit a function block? (a) define (b) return (c) finally (d) def 6. While defining a function which of the following symbol is used. (a) ; (semicolon) (b). (dot) (c) : (colon) (d) $ (dollar) 111 Python Functions 12th Compute

Use Quizgecko on...
Browser
Browser