12th CS MLM
12th CS MLM
STANDARD: XII
SUBJECT
COMPUTER SCIENCE
(MLM)
NAME : ________________________________
SECTION : _________________________________
LESSON 1 FUNCTION
1. The small sections of code that are used to perform a particular task is called
(A) Subroutines (B) Files (C) Pseudo code (D) Modules
2. Which of the following is a unit of code that is often defined within a greater code
structure?
(A) Subroutines (B) Function (C) Files (D) Modules
3. Which of the following is a distinct syntactic block?
(A) Subroutines (B) Function (C) Definition (D) Modules
4. The variables in a function definition are called as
(A) Subroutines (B) Function (C) Definition (D) Parameters
5. The values which are passed to a function definition are called
(A) Arguments (B) Subroutines (C) Function (D) Definition
6. Which of the following are mandatory to write the type annotations in the function
definition?
(A) { } (B) ( ) (C) [ ] (D) <>
7. Which of the following defines what an object can do?
(A) Operating System (B) Compiler (C) Interface (D) Interpreter
8. Which of the following carries out the instructions defined in the interface?
(A) Operating System (B) Compiler (C) Implementation (D) Interpreter
9. The functions which will give exact result when same arguments are passed are called
(A) Impure functions (B) Partial Functions (C) Dynamic Functions (D) Pure functions
10. The functions which cause side effects to the arguments passed are called
(A) impure function (B) Partial Functions (C) Dynamic Functions (D) Pure functions
1. Which of the following functions that build the abstract data type ?
(A) Constructors (B) Destructors (C) recursive (D)Nested
2. Which of the following functions that retrieve information from the data type?
(A) Constructors (B) Selectors (C) recursive (D)Nested
3. The data structure which is a mutable ordered sequence of elements is called
(A) Built in (B) List (C) Tuple (D) Derived data
4. A sequence of immutable objects is called
(A) Built in (B) List (C) Tuple (D) Derived data
5. The data type whose representation is known are called
(A) Built in datatype(B) Derived datatype (C) Concrete datatype (D) Abstract datatype
6. The data type whose representation is unknown are called
(A) Built in datatype (B) Derived datatype(C) Concrete datatype(D) Abstract datatype
7. Which of the following is a compound structure?
(A) Pair (B) Triplet (C) single (D) quadrat
8. Bundling two values together into one can be considered as
(A) Pair (B) Triplet (C) single (D) quadrat
9. Which of the following allow to name the various parts of a multi-item object?
(A) Tuples (B) Lists (C) Classes (D) quadrats
10. Which of the following is constructed by placing expressions within square brackets?
(A) Tuples (B) Lists (C) Classes (D) quadrats
Page 1 of 10
ALWAYS LIVE WITH GOD
TH
12 COMPUTER SCIENCE One Marks ISAAC EBINEZAR V
LESSON 3 SCOPING
1. Which of the following refers to the visibility of variablesin one part of a program to
another part of the same program.
(A) Scope (B) Memory (C) Address (D) Accessibility
2. The process of binding a variable name with an object is called
(A) Scope (B) Mapping (C) late binding (D) early binding
3. Which of the following is used in programming languages to map the variable and object?
(A) :: (B) := (C) = (D) ==
4. Containers for mapping names of variables to objects is called
(A) Scope (B) Mapping (C) Binding (D) Namespaces
5. Which scope refers to variables defined in current function?
(A) Local Scope (B) Global scope (C) Module scope (D) Function Scope
6. The process of subdividing a computer program into separate sub-programs is called
(A) Procedural Programming (B) Modular programming
(C)Event Driven Programming (D) Object oriented Programming
7. Which of the following security technique that regulates who canuse resources in a
computing environment?
(A) Password (B)Authentication (C) Access control (D) Certification
8. Which of the following members of a class can be handled only from within the class?
(A) Public members (B)Protected members (C) Secured members (D) Private members
9. Which members are accessible from outside the class?
(A) Public members (B)Protected members (C) Secured members (D) Private members
10. The members that are accessible from within the class and are also available to its sub-
classes is called
(A) Public members (B)Protected members (C) Secured members (D) Private members
1. The word comes from the name of a Persian mathematician Abu Ja’far Mohammed ibn-i
Musa al Khowarizmi is called?
(A) Flowchart (B) Flow (C) Algorithm (D) Syntax
2. From the following sorting algorithms which algorithm needs the minimum number of
swaps?
(A) Bubble sort (B) Insertion sort (C) Selection sort (D) All the above
3. Two main measures for the efficiency of an algorithm are
(A) Processor and memory (B) Complexity and capacity
(C) Time and space (D) Data and space
4. The algorithm that yields expected output for a valid input in called as
(A) Algorithmic solution (B) Algorithmic outcomes
(C) Algorithmic problem (D) Algorithmic coding
5. Which of the following is used to describe the worst case of an algorithm?
(A) Big A (B) Big S (C) Big W (D) Big O
6. Big Ω is the reverse of
(A) Big O (B) Big θ (C) Big A (D) Big S
7. Binary search is also called as
(A) Linear search (B) Sequential search (C) Random search (D) Half-interval search
8. The Θ notation in asymptotic evaluation represents
(A) Base case (B) Average case (C) Worst case (D) NULL case
9. If a problem can be broken into subproblems which are reused several times, the problem
possesses which property?
(A) Overlapping subproblems (B) Optimal substructure (C) Memoization(D) Greedy
10. In dynamic programming, the technique of storing the previously calculated values is
called?
(A) Saving value property (B) Storing value property (C) Memoization(D) Mapping
Page 2 of 10
ALWAYS LIVE WITH GOD
TH
12 COMPUTER SCIENCE One Marks ISAAC EBINEZAR V
LESSON 5 PYTHON – VARIABLES AND OPERATORS
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) <<< C) # D) <<
3. Which of the following shortcut is used to create new Python Program?
A) Ctrl + C B) Ctrl + F C) Ctrl + B D) Ctrl + N
4. Which of the following character is used to give comments in Python Program?
A) # B) & C) @ D) $
5. This symbol is used to print more than one item on a single line.
A) Semicolon(;) B) Dollor($) C) comma(,) D) Colon(:)
6. Which of the following is not a token ?
A) Interpreter B) Identifiers C) Keyword D) Operators
7. Which of the following is not a Keyword in Python ?
A) break B) while C) continue D) operators
8. Which operator is also called as Comparative operator?
A) Arithmetic B) Relational C) Logical D) Assignment
9. Which of the following is not Logical operator?
A) and B) or C) not D) Assignment
10. Which operator is also called as Conditional operator?
A) Ternary B) Relational C) Logical D) Assignment
LESSON 6 CONTROL STRUCTURES
1. How many important control structures are there in Python?
A) 3 B) 4 C) 5 D) 6
2. elif can be considered to be abbreviation of
A) nested if B) if..else C) else if D) if..elif
3. What plays a vital role in Python programming?
A) Statements B) Control C) Structure D) Indentation
4. Which statement is generally used as a place holder?
A) continue B) break C) pass D) goto
5. The condition in the if statement should be in the form of
A) Arithmetic or Relational expression B) Arithmetic or Logical expression
C) Relational or Logical expression D) Arithmetic
6. Which of the following is known as definite loop?
A) do..while B) while C) for D) if..elif
7. What is the output of the following snippet?
i=1
while True:
if i%3 ==0:
break
print(i,end=' ')
i +=1
A) 12 B) 123 C) 1234 D) 124
8. What is the output of the following snippet?
T=1
while T:
print(True)
break
A) False B) True C) 0 D) 1
9. Which amongst this is not a jump statement ?
A) for B) pass C) continue D) break
10. Which punctuation should be used in the blank?
if <condition>_
statements-block 1
else:
statements-block 2
A) ; B) : C) :: D) !
Page 3 of 10
ALWAYS LIVE WITH GOD
TH
12 COMPUTER SCIENCE One Marks ISAAC EBINEZAR V
LESSON 7 PYTHON FUNCTIONS
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)
7. In which arguments the correct positional order is passed to a function?
(a) Required (b) Keyword (c) Default (d) Variable-length
8. Read the following statement and choose the correct statement(s).
(I) In Python, you don’t have to mention the specific data types while defining function.
(II) Python keywords can be used as function name.
(a) I is correct and II is wrong (b) Both are correct
(c) I is wrong and II is correct (d) Both are wrong
9. Pick the correct one to execute the given statement successfully.
if ____ : print(x, " is a leap year")
(a) x%2=0 (b) x%4==0 (c) x/4=0 (d) x%4=0
10. Which of the following keyword is used to define the function testpython( ): ?
(a) define (b) pass (c) def (d) while
LESSON 8 STRINGS AND STRING MANIPULATION
1. Which of the following is the output of the following python code?
str1="TamilNadu"
print(str1[::-1])
(a) Tamilnadu (b) Tmlau (c) udanlimaT d) udaNlimaT
2. What will be the output of the following code?
str1 = "Chennai Schools"
str1[7] = "-"
(a) Chennai-Schools (b) Chenna-School (c) Type error (D) Chennai
3. Which of the following operator is used for concatenation?
(a) + (b) & (c) * d) =
4. Defining strings within triple quotes allows creating:
(a) Single line Strings (b) Multiline Strings (c) Double line Strings (d) Multiple Strings
5. Strings in python:
(a) Changeable (b) Mutable (c) Immutable (d) flexible
6. Which of the following is the slicing operator?
(a) { } (b) [ ] (c) < > (d) ( )
7. What is stride?
(a) index value of slide operation (b) first argument of slice operation
(c) second argument of slice operation (d) third argument of slice operation
8. Which of the following formatting character is used to print exponential notation in upper
case?
(a) %f (b) %E (c) %g (d) %n
9. Which of the following is used as placeholders or replacement fields which get replaced
along with format( ) function?
(a) { } (b) < > (c) ++ (d) ^^
10. The subscript of a string may be:
(a) Positive (b) Negative (c) Both (a) and (b) (d) Either (a) or (b)
Page 4 of 10
ALWAYS LIVE WITH GOD
TH
12 COMPUTER SCIENCE One Marks ISAAC EBINEZAR V
Page 5 of 10
ALWAYS LIVE WITH GOD
TH
12 COMPUTER SCIENCE One Marks ISAAC EBINEZAR V
LESSON 10 PYTHON CLASSES AND OBJECTS
1. Which of the following are the key features of an Object Oriented Programming language?
(a) Constructor and Classes (b) Constructor and Object
(c) Classes and Objects (d) Constructor and Destructor
2. Functions defined inside a class:
(a) Functions (b) Module (c) Methods (d) section
3. Class members are accessed through which operator?
(a) & (b) . (c) # (d) %
4. Which of the following method is automatically executed when an object is created?
(a) __object__( ) (b) __del__( ) (c) __func__( ) (d) __init__( )
5. A private class variable is prefixed with
(a) __ (b) && (c) ## (d) **
6. Which of the following method is used as destructor?
(a) __init__( ) (b) __dest__( ) (c) __rem__( ) (d) __del__( )
7. Which of the following class declaration is correct?
(a) class class_name (b) class class_name<> (c) class class_name: (d) class class_name[ ]
8. Which of the following is the output of the following program?
class Student:
def __init__(self, name):
self.name=name
print (self.name)
S=S
tudent(“Tamil”)
(a) Error (b) Tamil (c) name (d) self
9. Which of the following is the private class variable?
(a) __num (b) ##num (c) $$num (d) &&num
10. The process of creating an object is called as:
(a) Constructor (b) Destructor (c) Initialize (d) Instantiation
Page 6 of 10
ALWAYS LIVE WITH GOD
TH
12 COMPUTER SCIENCE One Marks ISAAC EBINEZAR V
1. Which commands provide definitions for creating table structure, deleting relations, and
modifying relation schemas.
a. DDL b. DML c. DCL d. DQL
2. Which command lets to change the structure of the table?
a. SELECT b. ORDER BY c. MODIFY d. ALTER
3. The command to delete a table including the structure is
a. DROP b. DELETE c. DELETE ALL d. ALTER TABLE
4. Queries can be generated using
a. SELECT b. ORDER BY c. MODIFY d. ALTER
5. The clause used to sort data in a database
a. SORT BY b. ORDER BY c. GROUP BY d. SELECT
Page 8 of 10
ALWAYS LIVE WITH GOD
TH
12 COMPUTER SCIENCE One Marks ISAAC EBINEZAR V
LESSON 16 DATA VISUALIZATION USING PYPLOT: LINE CHART, PIE CHART AND BAR CHART
1. Which is a python package used for 2D charts?
a. matplotlib.pyplot b. matplotlib.pip c. matplotlib.numpy d. matplotlib.plt
2. Identify the package manager for installing Python packages, or modules.
a. Matplotlib b. PIP c. plt.show( ) d. python package
3. Which of the following feature is used to represent data and information graphically?
a. Data List b. Data Tuple c. Classes and Objects d. Data Visualization
4. .......... is a collection of resources assembled to create a single unified visual display.
a. Interface b. Dashboard c. Objects d. Graphics
5. Which of the following module should be imported to visualize data and information in
Python?
a. csv b. getopt c. mysql d. matplotlib
6. ............ is a type of chart which displays information as a series of data points connected
by straight line segments.
a. csv (Line chart) b. Pie chart c. Bar chart d. All the above
7. Read the code:
import matplotlib.pyplot as plt
plt.plot(3,2)
plt.show()
Identify the output for the above coding.
a. b.
c. d.
Page 9 of 10
ALWAYS LIVE WITH GOD
TH
12 COMPUTER SCIENCE One Marks ISAAC EBINEZAR V
Page 10 of 10
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 2 Marks ISAAC EBINEZAR V
1. What is a subroutine? 10. What do you mean by Namespaces?
Subroutines are the basic building blocks Namespaces are containers for mapping
of computer programs. names of variables to objects.
Subroutines are small sections of code that Ex: a:=5
are used to perform a particular task that 11. What is an Algorithm?
can be used repeatedly. An algorithm is a finite set of instructions to
In Programming languages these accomplish a particular task.
subroutines are called as Functions. It is a step-by-step procedure for solving a
2. Write the inference you get from X:=(78). given problem.
Let us consider the example X:=(78). An algorithm can be implemented in any
X:=(78) has an expression in it but (78) is suitable programming language.
not itself an expression. 12. What is Sorting?
Rather, it is a function definition. Sorting is a process to arranging group of
Definitions bind values to names. items in an ascending or descending order.
In this case the value 78 being bound to Sorting algorithms are 1) bubble sort,
the name „X‟. 2) insertion sort, and 3) selection sort.
3. What is abstract data type? 13. What is searching? Write its types.
Abstract Data type (ADT) is a type (or class) Searching is the process to finding
for objects whose behavior is defined by a set particular items from the list.
of value and a set of operations. Searching types are :
4. Differentiate constructors and selectors. 1) Linear search and 2) Binary search.
Constructors are functions that build the 14. What are the different modes that can be
abstract data type. used to test Python Program ?
Selectors are functions that retrieve In Python, programs can be written in two
information from the data type. ways namely
5. What is a Pair? Give an example. 1) Interactive mode: allows us to write codes in
Any way of bundling two values together Python command prompt (>>>)
into one can be considered as a pair. 2) Script mode : programs can be written and
Lists are a common method to do so. stored as separate file with the extension .py
Therefore List can be called as Pairs. and executed.
Example: lst := [10, 20] 15. Write short notes on Tokens.
lst[(0, 10), (1, 20)] - where Python breaks each logical line into a
sequence of elementary lexical components
known as Tokens. The normal token types
are
6. What is a List? Give an example. 1) Identifiers, 2) Keywords,
List is constructed by placing expressions 3) Operators, 4) Delimiters and 5) Literals.
within square brackets separated by White space separation is necessary
commas. between tokens.
Example Ist:= [10, 20]. 16. What are the different operators that can
7. What is a Tuple? Give an example. be used in Python ?
A tuple is a comma-separated sequence of Operators are categorized as
values surrounded with parentheses. 1) Arithmetic, 2) Relational
Tuple is similar to a list. 3) Logical, 4) Assignment and
you cannot change the elements of a tuple 5) Conditional (or) Ternary operator.
once it is assigned whereas in a list, 17. What is a literal? Explain the types of
elements can be changed. literals ?
Example colour= ('red', 'blue', 'Green') Literal is a raw data given to a variable or
8. What is a scope? constant. In Python, there are various types
Scope refers to the visibility of variables, of literals.
parameters and functions in one part of a 1) Numeric 2) String 3) Boolean
program to another part of the same 18. Write short notes on Exponent data?
program. An Exponent data contains decimal digit
9. What is Mapping? part, decimal point, exponent part followed
The process of binding a variable name by one or more digits.
with an object is called mapping. Ex: 12.E04, 24.e04
= (equal to sign) is used in programming 19. List the control structures in Python.
languages to map the variable and object. There are three important control structures
1) Sequential
2) Alternative or Branching
3) Iterative or Looping
Page 1 of 4
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 2 Marks ISAAC EBINEZAR V
20. What are the main advantages of 29. How will you access the list elements in
function? reverse order?
1) It avoids repetition and makes high degree Python enables reverse or negative
of code reusing. indexing for the list elements.
2) It provides better modularity for your Thus, python lists index in opposite order.
application. The python sets -1 as the index value for
21. Mention few examples of a DBMS. the last element in list and -2 for the
Examples of popular DBMS: preceding element and so on.
Dbase, This is called as Reverse Indexing.
FoxPro 30. What is class?
22. List some examples of RDBMS. Class is the main building block in Python.
Examaple of RDBMS: Object is a collection of data and function
MySQL, that act on those data.
Oracle, Class is a template for the object.
MS-Access etc., 31. What is instantiation?
23. Write the expansion of (i) SWIG (ii) MinGW According to the concept of OOP‟s,
i) SWIG- Simplified Wrapper Interface objects are also called as instances of a
Generator- Both C and C++ class.
ii) MinGW- Minimalist GNU for Windows The process of creating object is called as
24. Mention the two ways to read a CSV file “Class Instantiation”.
using Python. Syntax:
There are two ways to read a CSV file. Object_name = class_name( )
1. Use the csv module‟s reader function 32. How will you create constructor in
2. Use the DictReader class. Python?
25. Write note on break statement. In Python, there is a special function
The break statement terminates the loop called “init” which act as a Constructor.
containing it. Control of the program flows It must begin and end with double
to the statement immediately after the body underscore.
of the loop. General format:
A while or for loop will iterate till the def _ _init_ _(self, [args ……..]):
condition is tested false, but one can even <statements>
transfer the control out of the loop 33. What is the purpose of Destructor?
(terminate) with help of break statement. Destructor is also a special method to
Syntax: destroy the objects.
break In Python, _ _del_ _( ) method is used as
26. How will you delete a string in Python? destructor.
Python will not allow deleting a particular It is just opposite to constructor.
character in a string. Destructor is also a special method gets
Whereas you can remove entire string execution automatically when an object
variable using del command. exits from the scope.
Example: 34. What is data consistency?
>>> str1="How about you" Data Consistency means that data values
>>>del str1 are the same at all instances of a database.
27. What is slicing? On live data, it is being continuously
Slice is a substring of a main string. updated and added, maintaining the
A substring can be taken from the original consistency of data can become a
string by using [ ] operator and index or challenge.
subscript values. But RDBMS handles it by itself.
Thus, [ ] is also known as slicing operator. 35. What is normalization?
Using slice operator, you have to slice one Database normalization was first proposed by
or more substrings from a main string. Dr. Edgar F Codd as an integral part of
General format of slice operation: RDBMS in order to reduce data redundancy
str[start:end] and improve data integrity.
Where start is the beginning index and end 36. What is use of next( ) function?
is the last index value of a character in the Since the row heading is also get sorted, to
string. avoid that the first row should be skipped.
28. What is CSV File? This is can be done by using the command
A CSV file is a human readable text file “next( )”. The list is sorted and displayed.
where each line has a number of fields, The next( ) function returns the next item
separated by commas or some other from the iterator. It can also be used to skip
delimiter. a row of the csv file.
Page 2 of 4
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 2 Marks ISAAC EBINEZAR V
37. What is the use of cd command. Give an 43. List the types of Visualizations in
example. Matplotlib.
To change a directory 'cd' command is There are many types of Visualizations under
used. Matplotlib. Some of them are:
For example to goto the directory pyprg, Line plot
type the command 'cd pyprg' in the Scatter plot
command prompt. Histogram
38. What is the use of modules? Box plot
We use modules to break down large Bar chart and
programs into small manageable and Pie chart
organized program. 44. Write the difference between the following
Furthermore, modules provide reusability functions: plt.plot([1,2,3,4]),
of code. plt.plot([1,2,3,4], [1,4,9,16]).
We can define our most used functions in a plt.plot([1,2,3,4]) plt.plot([1,2,3,4], [1,4,9,16])
module and import it, instead of copying If you provide a single This plot takes many
their definitions into different programs. list or array to the plot () arguments, but the first
39. What is the advantage of declaring a command, matplotlib two here are 'x' and 'y'
column as “INTEGER PRIMARY KEY” assumes it is a coordinates. This
If a column of a table is declared to be an sequence of y values, means, you have 4 co-
INTEGER PRIMARY KEY, and automatically ordinates according to
then whenever a NULL will be used as an generates the x values these lists: (1,1), (2,4),
input for this column, the NULL will be for you. Since python (3,9) and (4,16).
automatically converted into an integer ranges start with 0, the
which will one larger than the highest value default x vector has the
so far used in that column. same length as y but
If the table is empty, the value 1 will be starts with 0. Hence the
used. x data are [0, 1, 2, 3].
40. Which method is used to fetch all rows 45. Mention the default modes of the File.
from the database table? The following are the default mode of the file
The fetchall() method is used to fetch all Mode Description
rows from the database table
Example: 'r' Open a file for reading. (default)
import sqlite3 't' Open in text mode. (default)
connection =
46. Differentiate interface and implementation.
sqlite3.connect("Academy.db")
cursor = connection.cursor() Interface Implementation
cursor.execute("SELECT * FROM Interface just defines Implementation carries
student") what an object can do, out the instructions
print("fetchall:") but won‟t actually do it. defined in the interface.
result = cursor.fetchall() 47. Differentiate Unique and Primary Key
for r in result: constraint.
print(r) Unique Key constraint Primary Key constraint
41. What is Data Visualization? This constraint ensures This constraint declares
Data Visualization is the graphical that no two rows have a field as a Primary key
representation of information and data. the same value in the which helps to uniquely
The objective of Data Visualization is to specified columns. identify a record.
communicate information visually to users. The UNIQUE constraint
For this, data visualization uses statistical Primary Key constraint
can be applied only to
graphics. will help us to uniquely
fields that have also
Numerical data may be encoded using identify a record, it is
been declared as NOT
dots, lines, or bars, to visually also set NOT NULL
NULL.
communicate a quantitative message. will not be NULL and
42. List the general types of data The primary key does
should not be
visualization. not allow NULL values.
duplicated.
Charts 48. Write the difference between table
Tables constraint and column constraint?
Graphs Table constraint apply to a
Maps Table constraint
group of one or more columns.
Infographics Column constraint apply only
Dashboards Column constraint
to individual column.
Page 3 of 4
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 2 Marks ISAAC EBINEZAR V
49. Differentiate del with remove() function of 54. Write the syntax of creating a Tuple with
List. n number of elements.
del remove( ) # Tuple with n number elements:
del statement is remove() function is Tuple_Name = (E1, E2, E2 ……. En)
used to delete used to delete # Elements of a tuple without parenthesis:
elements whose elements of a list if its Tuple_Name = E1, E2, E3 ….. En
index is known index is unknown. 55. What will be the output of the following
del statement can remove() function can python code?
also be used to also be used to delete str1 = “School”
delete entire list. one or more elements print(str1*3)
if the index value is not Output:
known. SchoolSchoolSchool
Ex: del marks[1] Ex. Marks.remove(63) 56. Write is the syntax of if..else statement.
50. Differentiate compiler and interpreter. Syntax:
Compiler Interprter if<condition>:
Scans the entire Translates program statements-block 1
program and one statement at a else:
translates it as a time. statements-block 2
whole into machine 57. What will be the value of x in following
code. python code?
It generates the error It continues translating List1=[2,4,6[1,3,5]]
message only after the program until the x=len(List1)
scanning the whole first error is met, in Output:
program. which case it stops. 4
Hence debugging is Hence debugging is 58. What is the output of the following
comparatively hard. easy. program?
51. What is the difference between SQL and class Sample:
MySQL? __num=10
Structured Query Language is a defdisp(self):
SQL language used for accessing print(self.__num)
databases. S=Sample()
S.disp()
MYSQLis a database management
print(S.__num)
system, like SQL Server, Oracle,
MySQL Output:
Informix, Postgres, etc. MySQL is a
10
RDBMS.
line 7, in <module>
52. Which method is used to connect a print(S.__num)
database? Give an example. AttributeError: 'Sample' object has no
Step 1 import sqlite3 attribute '__num'
Step 2 create a connection using connect () 59. Which of the following is a normal
method and pass the name of the function definition and which is recursive
database File function definition
Step 3 Set the cursor object cursor = i) let sum x y:
connection. cursor () return x + y
Example: ii) letdisp :
import sqlite3 print „welcome‟
iii) let rec sum num:
connection = sqlite3.connect ("Academy.db") if (num!=0) then return
cursor = connection.cursor() num+sum(num-1)
53. How to set the limit for recursive else
function? Give an example. returnnum
python stops calling recursive function after ans:
1000 calls by default. i) normal function
It also allows you to change the limit using ii) normal function
sys.setrecursionlimit (limit_value).
Example: iii) recursive function
import sys 60. Write a query that selects all students
sys.setrecursionlimit(3000) whose age is less than 18 in order wise.
def fact(n): SELECT * FROM Student WHERE Age <=
if n == 0: 18 ORDER By Name;
return 1
else:
return n * fact(n-1)
print(fact (2000))
Page 4 of 4
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 3 Marks ISAAC EBINEZAR V
1. Mention the characteristics of Interface. 6. What are the factors that influence time
1) The class template specifies the interfaces and space complexity.
to enable an object to be created and The efficiency of an algorithm depends on
operated properly. how efficiently it uses time and memory
2) An object's attributes and behaviour is space.
controlled by sending functions to the The time efficiency of an algorithm is
object. measured by different factors.
2. Why strlen is called pure function? 1) Speed of the machine
strlen is a pure function because the 2) Compiler and other system Software tools
function takes one variable as a parameter, 3) Operating System
and accesses it to find its length. 4) Programming language used
This function reads external memory but 5) Volume of data required
does not change it, and the value returned 7. Discuss about Algorithmic complexity and
derives from the external memory its types.
accessed. The complexity of an algorithm f (n) gives the
3. Which strategy is used for program running time and/or the storage space
designing? Define that Strategy. required by the algorithm in terms of n as the
We are using here a powerful strategy for size of input data.
designing programs: 'wishful thinking'. Time Complexity : The Time complexity of
Wishful Thinking is the formation of beliefs an algorithm is given by the number of
steps taken by the algorithm to complete
and making decisions according to what
the process.
might be pleasing to imagine instead of by Space Complexity : Space complexity of
appealing to reality. an algorithm is the amount of memory
4. What are the different ways to access the required to run to its completion. The
elements of a list. Give example. space required by an algorithm is equal to
1) Multiple assignment: the sum of the following two components:
Which unpacks a list into its elements and 1) A fixed part
binds each element to a different name. 2) A variable part
Ex: lst := [10, 20] 8. Write a note on Asymptotic notation.
x, y := lst Asymptotic Notations are languages that
In the above example x will become10 uses meaningful statements about time
and y will become 20. and space complexity.
2) Element selection operator: The following three asymptotic notations
Unlike a list literal, a square-brackets are mostly used to represent time
expression directly following another complexity of algorithms:
expression does not evaluate to a list (i) Big O : Big O is often used to describe the
value, but instead selects an element from worst-case of an algorithm.
the value of the preceding expression. (ii) BigΩ : Big Omega is the reverse Big O,
Big Omega is used to describe the
Ex: lst[0]
lower bound (best-case).
10 (iii) BigΘ : When an algorithm has a
lst[1] complexity with lower bound =
20 upper bound, say that an
5. Why access control is required? algorithm has a complexity O (n
Access control is a security technique that log n) and Ω (n log n), it‟s actually
regulates who or what can view or use has the complexity Θ (n log n)
resources in a computing environment. 9. What do you understand by Dynamic
It is a fundamental concept in security that programming?
minimizes risk to the object. Dynamic programming is an algorithmic
In other words access control is a selective design method that can be used when the
restriction of access to data. solution to a problem can be viewed as the
In Object oriented programming languages result of a sequence of decisions.
it is implemented through access modifiers. Steps to do Dynamic programming
1) The given problem will be divided into
smaller overlapping sub-problems.
2) An optimum solution for the given problem
can be achieved by using result of smaller
sub-problem.
3) Dynamic algorithms uses Memoization.
Page 1 of 10
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 3 Marks ISAAC EBINEZAR V
10. Explain Ternary operator with examples. 14. How recursive function works?
Ternary operator is also known as 1) Recursive function is called by some
conditional operator that evaluate external code.
something based on a condition being true 2) If the base condition is met then the
or false. program gives meaningful output and exits.
It simply allows testing a condition in a 3) Otherwise, function does some required
single line replacing the multiline if-else processing and then calls itself to continue
making the code compact. recursion.
The Syntax conditional operator is,
15. What are the points to be noted while
Variable Name = [on_true] if [Test
expression] else [on_false] defining a function?
Example : When defining functions there are multiple
min= 49 if 49<50 else 50 # min = 49 things that need to be noted;
11. What are string literals? Explain. 1) Function blocks begin with the keyword
In Python a string literal is a sequence of “def” followed by function name and
characters surrounded by quotes. parenthesis().
Python supports single, double and triple 2) If any input parameters are present should
quotes for a string. be placed within these parentheses when
A character literal is a single character you define a function.
surrounded by single or double quotes. 3) The code block always comes after a colon
The value with triple-quote "' '" is used to (:) and is indented.
give multi-line string literal. 4) The statement “return [expression]” exits a
A Character literal is also considered as function, optionally passing back an
string literal in Python. expression to the caller. A “return” with no
Ex: arguments is the same as return None.
strings = "This is Python" 16. What is the use of format( )? Give an
char = "C" example.
multiline_str = "'This is a multiline string
The format( ) function used with strings is
with more than one line code."'
print (strings) very versatile and powerful function
print (char) usedfor formatting strings.
print (multiline_str) The curly braces { } are used as
Output: placeholders or replacement fields
This is Python whichget replaced along with format( )
C function.
This is a multiline string with more than one Example:
line code. num1=int (input("Number 1: "))
12. What happens when we modify global num2=int (input("Number 2: "))
variable inside the function? print ("The sum of { } and { } is {
When we try to modify global variable }".Format(num1,
inside the function an UnboundLocal Error num2,(num1+num2)))
will occur. Output
Without using the global keyword we Number 1: 34
cannot modify the global variable inside the Number 2: 54
function but we can only access the global The sum of 34 and 54 is 88
variable. 17. Write a note about count( ) function in
13. What is composition in functions?
python.
The value returned by a function may be
used as an argument for another function Returns the number of substrings occurs
in a nested manner. This is called within the given range. Remember that
composition. substring may be a single character. Range
For example, if we wish to take a numeric (beg and end) arguments are optional. If it is
value or an expression as a input from the not given, python searched in whole string.
user, we take the input string from the user Search is case sensitive.
using the function input() and apply eval() Syntax:
function to evaluate its value count(str, beg, end)
Ex: Ex:
>>> n1 = eval (input ("Enter a number: ")) >>> str1="Raja RajaChozhan"
>>>print(str1.count('Raja'))
2
Page 2 of 10
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 3 Marks ISAAC EBINEZAR V
18. What are the difference between list and 22. What is the role of DBA?
Tuples? Database Administrator or DBA is the one
1) The elements of a list are changeable who manages the complete database
(mutable) whereas the elements of a tuple management system.
DBA takes care of the security of the
are unchangeable (immutable), this is the DBMS, managing the license keys,
key difference between tuples and list. managing user accounts and access etc.
2) The elements of a list are enclosed within 23. Write a note on different types of DBMS
square brackets. But, the elements of a users.
tuple are enclosed by paranthesis. 1) Database Administrators:
3) Iterating tuples is faster than list. Database Administrator or DBA is the
19. List out the set operations supported by one who manages the complete
python. database management system. DBA
As you learnt in mathematics, the python is takes care of the security of the DBMS,
managing the license keys, managing
also supports the set operations such as, user accounts and access etc.
1) Union, 2) Application Programmers or Software
2) Intersection, Developers:
3) difference and This user group is involved in
4) Symmetric difference. developing and designing the parts of
20. What are the difference between List and DBMS.
Dictionary? 3) End User:
1) List is an ordered set of elements. But, a End users are the one who store,
dictionary is a data structure that is used retrieve, update and delete data.
4) Database designers:
for matching one element (Key) with Database designers are responsible
another (Value). for identifying the data to be stored in
2) The index values can be used to access a the database for choosing appropriate
particular element. But, in dictionary key structures to represent and store the
represents index. Remember that, key may data.
be a number of a string. 24. What is a constraint? Write short note on
3) Lists are used to look up a value whereas Primary key constraint.
a dictionary is used to take one value and Constraint is a condition applicable on a field
look up another value. or set of fields.
21. What are class members? How do you Primary Key Constraint:
define it? This constraint declares a field as a
Variables defined inside a class are called Primary key which helps to uniquely
as “Class Variable” and functions are identify a record.
It is similar to unique constraint except
called as “Methods”.
that only one field of a table can be set as
Class variable and methods are together
primary key.
known as members of the class. The primary key does not allow NULL
The class members should be accessed values.
through objects or instance of class. Example showing Primary Key Constraint
A class can be defined anywhere in a in the student table:
Python program. CREATE TABLE Student
Example: (
class Sample: Admno integer PRIMARY KEY, →
x, y = 10, 20 #class variables Primary Key constraint
S=Sample( ) # class instantiation Name char(20) NOT NULL,
print("Value of x = ", S.x) Gender char(1),
print("Value of y = ", S.y) Age integer,
print("Value of x and y = ", S.x+S.y) Place char(10),
);
Page 3 of 10
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 3 Marks ISAAC EBINEZAR V
25. Write the use of Savepoint command with 29. What is SQLite?What is it advantage?
an example. SQLite is a simple relational database
The SAVEPOINT command is used to system, which saves its data in regular data
temporarily save a transaction so that you files within internal memory of the computer.
can rollback to the point whenever Advantages:
required. It is designed to be embedded in
The different states of our table can be applications, instead of using a separate
saved at anytime using different names database server program such as
and the rollback to that state can be done MySQLor Oracle.
using the ROLLBACK command.
SQLite is fast, rigorously tested, and
SAVEPOINT savepoint_name;
Example: SAVEPOINT A; flexible, making it easier to work.
26. What are the applications of scripting Python has a native library for SQLite.
language? 30. Write any three uses of data visualization.
1) To automate certain tasks in a program Data Visualization help users to analyze
2) Extracting information from a data set and interpret the data easily.
3) Less code intensive as compared to It makes complex data understandable
traditional programming language and usable.
4) can bring new functions to applications Various Charts in Data Visualization
and glue complex systems together helps to show relationship in the data for
27. What is MinGW? What is its use? one or more variables.
31. Explain Cartesian Product with a suitable
MinGW refers to a set of runtime header example.
files, used in compiling and linking the Cross product is a way of combining two
code of C, C++ and FORTRAN to be run relations. The resulting relation contains,
on Windows Operating System. both relations being combined.
MinGw-W64 (version of MinGW) is the A x B means A times B, where the relation
best compiler for C++ on Windows. A and B have different attributes.
To compile and execute the C++ program, This type of operation is helpful to merge
you need „g++‟ for Windows. columns from two relations.
MinGW allows to compile and execute C++ Example:
program dynamically through Python Table A Table B
program using g++. Stu name cour subject
28. What is sys.argv? What does it contain? dno se
sys.argv is the list of command-line cs1 Kannan cs28 Big Data
arguments passed to the Python program.
cs4 Padmaja cs25 python
argv contains all the items that come via
the command-line input, it's basically a list
programmin
holding the command-line arguments of g
the program.
Cartesian product :
To use sys.argv, import sys should be Table A = 2
used. Table B = 2
The first argument, sys.argv[0] contains the Table A x B = 2 X 2=4
name of the python program (example stu name Cour subject
pali.py) dno se
and sys.argv[1] is the next argument
cs1 Kannan cs28 Big Data
passed to the program (here it is the C++
file), which will be the argument passed cs1 Kannan cs25 python
through main ( ). rogramming
For example cs4 Padmaja cs28 Big Data
main(sys.argv[1]) cs4 Padmaja cs25 python
programming
Page 4 of 10
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 3 Marks ISAAC EBINEZAR V
32. What are the assignment operators that 34. Write a SQL statement using DISTINCT
can be used in Python? keyword.
In Python, = is a simple assignment The DISTINCT keyword is used along with
operator to assign values to variable. the SELECT command to eliminate
Let a = 5 and b = 10 assigns the value 5 to duplicate rows in the table.
a and 10 to b. This helps to eliminate redundant data.
There are various compound operators in For Example:
Python like +=, -=, *=, /=, %=, **= and //= Adm Name Gende Age Place
are also available. no r
Operator Description Example 100 Ashish M 17 Chennai
Assume x=10 101 Adarsh M 18 Delhi
>>> x=10 102 Akshith M 17 Bangalor
Assigns right side
=
operands to left variable
>>> e
b=”Computer” 103 Ayush M 18 Delhi
Added and assign back
>>> x+=20 104 Abinand M 18
+= the result
# x=x+20 Chennai
to left operand h
Subtracted and assign SELECT DISTINCT Place FROM Student;
>>> x-=5
-= back the Will display the following data as follows :
# x=x-5
result to left operand
Multiplied and assign Place
>>> x*=5
*= back the Chennai
# x=x*5
result to left operand
Divided and assign back Bangalore
>>> x/=2
/= the Delhi
# x=x/2
result to left operand
33. Write short notes on Escape sequences 35. What is the difference between Select and
Project command?
with examples. SELECT project
In Python strings, the backslash "\" is a The SELECT The projection
special character, also called the "escape" operation is used for eliminates all attributes
character. selecting a subset of the input relation but
It is used in representing certain with tuples according those mentioned in the
whitespace characters: "\t" is a tab, "\n" is to a given condition. projection list.
a newline, and "\r" is a carriage return. Select filters out all The projection method
For example to print the message "It's tuples that do not defines a relation that
raining", the Python command is satisfy the condition. contains a vertical
>>> print ("It\'s rainning") subset of Relation.
symbol : σ symbol : Π
It's rainning
Python supports the following escape 36. Differentiate pure and impure function.
sequence characters. Pure Function Impure Function
Escape
sequence Description Example Output The return value of the The return value of
character pure functions solely the impure functions
\\ Backslash >>> print("\\test") \test depends on its does not solely
>>> arguments passed. depend on its
\‟ Single-quote Doesn't Hence, if you call the arguments passed.
print("Doesn\'t")
\” Double-quote
>>>
"Python"
pure functions with the Hence, if you call the
print("\"Python\"") same set of impure functions with
print("Python","\n", Python arguments, you will the same set of
\n New line
"Lang..") Lang.. always get the same arguments, you might
print("Python","\t"," Python return values. get the different return
\t Tab
Lang..") Lang.. They do not have any values For example,
side effects. random(), Date().
They do not modify the They may modify the
arguments which are arguments which are
passed to them passed to them
Page 5 of 10
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 3 Marks ISAAC EBINEZAR V
37. List the differences between break and 40. Mention the difference between fetchone()
continue statements. and fetchmany()
Break continue fetchone( ) fetchmany( )
The break statement Continue statement The fetchone() Displaying specified
terminates the loop unlike the break method returns the number of records is
containing it. statement is used to next row of a query done by using
Control of the program skip the remaining result set or None in fetchmany(n).
flows to the statement part of a loop and case there is no row
immediately after the start with next left.
body of the loop. iteration. Using while loop and This method returns the
Syntax: Syntax: fetchone() method we number of rows of the
break continue can display all the result set.
38. What is the difference between the write records from a table.
mode and append mode. Ex: Ex:
write mode append mode res=cursor.fetchone( ) result=cursor.fetchmany(3)
„w‟ „a‟ 41. Differentiate PYTHON and C++
Open a file for writing. Open for appending at S. PYTHON C++
Creates a new file if it the end of the file NO
does not exist or without truncating it. 1 Python is C++ is typically a
truncates the file if it Creates a new file if it typically an "compiled"
exists. does not exist. "interpreted" language
f = open f = open language
("sample.txt",'w') ("sample.txt",'a')
2 Python is a C++ is compiled
39. What is the difference between
reader()method and DictReader() class?
dynamic-typed statically typed
reader() DictReader() language language
The reader function is To read a CSV file into 3 Data type is not Data type is
designed to take each a dictionary can be required while required while
line of the file and done by using declaring declaring variable
make a list of all DictReader method of variable
columns. csv module which 4 It can act both as It is a general
creates an object which scripting and purpose language
maps data to a general purpose
dictionary. language
Using this function one DictReader works by 42. How to define constructor and destructor
can read data from csv reading the first line of in Python?
files of different the CSV and using Constructor:
formats like quotes (" each comma separated In Python, there is a special function
"), pipe (|) and comma value in this line as a called “init” which act as a Constructor.
(,). dictionary key. It must begin and end with double
underscore.
csv.reader() work with csv.DictReader() work General format:
list/tuple. with dictionary def _ _init_ _(self, [args ……..]):
<statements>
Destructor:
Destructor is also a special method to
destroy the objects.
In Python, _ _del_ _( ) method is used
as destructor.
General format:
def _ _del_ _(self):
<statements>
Page 6 of 10
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 3 Marks ISAAC EBINEZAR V
43. Explain the difference between del and clear() in dictionary with an example.
clear( ) del
The function clear() is used to delete all the The del statement deletes entire list.
elements in list, it deletes only the
elementsand retains the list.
Syntax: Syntax:
List.clear( ) del List
Ex: Ex:
>>>MyList.clear( ) >>>MySubjects = ['Tamil', 'CS', 'Maths']
>>> print(MyList) >>> del MySubjects
[] >>> print(MySubjects)
NameError: name 'MySubjects' is not defined
clear() function removes only the elements Deletes the list MySubjects entirely.Which means,
and retains the list. the list MySubjects has been completely deleted.
44. Write any three DDL commands.
Command Usages Syntax Example
Create To create tables in CREATE TABLE <table-name> CREATE TABLE Student
the database. (<column name><data (Admno integer,
type>[<size>] Name char(20),
(<column name><data Gender char(1),
type>[<size>]……); Age integer,
Place char(10),);
Alter Alters the structure ALTER TABLE <table-name> ALTER TABLE student
of the database. ADD <column-name><data ADD address char(50);
type><size>;
Drop Delete tables from DROP TABLE table-name; DROP TABLE Student;
database.
Truncate Remove all records TRUNCATE TABLE table- TRUNCATE TABLE
from a table, also name; Student;
release the space
occupied by those
records.
45. Differentiate ceil() and floor() function?
Function Description Syntax Example
import math
x= 26.7
y= -26.7
Returns the smallest integer print (math.ceil (x))
ceil ( ) math.ceil (x)
greater than or equal to x print (math.ceil (y))
Output:
27
-26
import math
x=26.7
y=-26.7
Returns the largest integer less print (math.floor (x))
floor ( ) math.floor (x)
than or equal to x print (math.floor (y))
Output:
26
-27
Page 7 of 10
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 3 Marks ISAAC EBINEZAR V
46. Write a short about the followings with suitable example:
(a) capitalize( ) (b) swapcase( )
Syntax Description Example
capitalize( ) Used to capitalize the firstcharacter >>> city="chennai"
of the string >>> print(city.capitalize())
Chennai
swapcase( ) It will change case of every >>>str1="tAmiLNaDu"
character to its opposite case vice- >>>print(str1.swapcase())
versa. TaMIlnAdU
47. Write a shot note about sort().
Description Syntax
Sorts the element in list List.sort(reverse=True|False, key=myFunc)
Both arguments are optional MyList=['Thilothamma', 'Tharani', 'Anitha', 'SaiSree',
If reverse is set as True, list sorting is
'Lavanya']
in descending order. MyList.sort( )
Ascending is default. print(MyList)
Key=myFunc; “myFunc” - the name ofMyList.sort(reverse=True)
print(MyList)
the user defined function that specifies
the sorting criteria. Output:
['Anitha', 'Lavanya', 'SaiSree', 'Tharani', 'Thilothamma']
Note: sort( ) will affect the original list.
['Thilothamma', 'Tharani', 'SaiSree', 'Lavanya', 'Anitha']
48. Write a Python program to display the 50. Identify Which of the following are
given pattern constructors and selectors?
COMPUTER (a) N1:=number() (b) accetnum(n1)
COMPUTE (c) displaynum(n1) (d) eval(a/b)
COMPUT (e) x,y:= makeslope (m), makeslope(n)
COMPU (f) display()
COMP Ans:
COM (a) Constructor (b) Selector
CO (c) Selector (d) Selector
C (e) Constructor (f) selector
Coding: 51. Identify Which of the following are List,
str="COMPUTER" Tuple and class ?
index=len(str) (a) arr [1, 2, 34]
for i in str: (b) arr (1, 2, 34)
print(str[:index]) (c) student [rno, name, mark]
index-=1 (d) day:= (‘sun’, ‘mon’, ‘tue’, ‘wed’)
49. Write a program to display (e) x:= [2, 5, 6.5, [5, 6], 8.2]
A (f) employee [eno, ename, esal, eaddress]
AB Ans:
ABC (a) List (b) Tuple (c) Class
ABCD (d) Tuple (e) List (f) Class
ABCDE 52. What will be the output of the given
i=65 python program?
while(i<=70): str1 = "welcome"
for j in range(65,i): str2 = "to school"
print(chr(j),end='\t') str3=str1[:2]+str2[len(str2)-2:]
print(end='\n') print(str3)
i+=1 Output : Weol
53. What will be the output of the following
code?
list = [2**x for x in range(5)]
print(list)
Output : [1,2,4,8,16]
Page 8 of 10
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 3 Marks ISAAC EBINEZAR V
54. Identify the scope of the variables in the 59. What is the output of the following
following pseudo code and write its program?
output class Greeting:
color:= 'Red' def __init__(self, name):
mycolor(): self.__name = name
b:='Blue' def display(self):
myfavcolor(): print("Good Morning ", self.__name)
g:='Green' obj=Greeting('BinduMadhavan')
print color, b, g obj.display()
myfavcolor() Output:
print color, b Good Morning BinduMadhavan
mycolor() 60. Find the error in the following program to
print color get the given output?
Output: class Fruits:
Red Blue Green def __init__(self, f1, f2):
Red Blue self.f1=f1
Red self.f2=f2
55. Using if..else..elif statement write a def display(self):
suitable program to display largest of 3 print("Fruit 1 = %s, Fruit 2 = %s"
numbers. %(self.f1, self.f2))
n1=int(input(“Enter the First Number”)) F = Fruits ('Apple', 'Mango')
n2=int(input(“Enter the Second Number”)) delF.display
n3=int(input(“Enter the Third Number”)) F.display()
if(n1>=n2 and n1>=n3): Output
print(n1,”is the largest number”) Fruit 1 = Apple, Fruit 2 = Mango
elif(n2>=n1 and n2>=n3): Error:
print(n2,”is the largest number”) line8, in <model>
else: Del F.display
print(n3,”is the largest number”) Attribute Error: display
56. Write the syntax of while loop. (The statement “delF.display” should be
Syntax: removed to get the given output.)
while<condition>: Correct Program:
statements block 1 class Fruits:
[else: def __init__(self, f1, f2):
statements block2] self.f1=f1
57. Write a Python code to check whether a self.f2=f2
given year is leap year or not. def display(self):
year=int(input(“enter a year:”)) print("Fruit 1 = %s, Fruit 2 = %s" %(self.f1,
if year%4==0: self.f2))
print(year,”is a Leap Year”) F = Fruits ('Apple', 'Mango')
else: F.display( )
print(year,”is not a Leap Year”) 61. Write note on if..else structure.
58. Write a class with two private class The if ..elsestatement provides control to
variables and print the sum using a check the true block as well as the false
method. block.
Program: Syntax:
class Sample: if<condition>:
def __init__(self,n1,n2): statements-block 1
Self.__n1=n1 else:
statements-block 2
Self.__n2=n2 if..else statement thus provides two
def sum(self): possibilities and the condition determines
print(“Class variable1:”,self.__n1) which BLOCK is to be executed.
print(“Class variable2:”,self.__n2) Example:
print(“Sum:”,self.__n1+self.__n2) a = int(input("Enter any number :"))
S=Sample(10,20) if a%2==0:
S.sum( ) print (a, " is an even number")
Output: else:
Class Variable1: 10 print (a, " is an odd number")
Class Variable1: 20 Output 1:
Sum:30 Enter any number :56
56 is an even number
Page 9 of 10
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 3 Marks ISAAC EBINEZAR V
62. What is the use of Where Clause. Give a 67. Write a Python program to modify an
python statement Using the where clause. existing file.
The WHERE clause is used to extract only import csv
those records that fulfill a specified row = [„3‟, „Meena‟,‟Bangalore‟]
with open(„student.csv‟,„r‟,newline„=‟)as readFile:
condition. reader = csv.reader(readFile)
For example we are going to display the lines = list(reader)
different grades scored by male students lines[3] = row
from “student table” with open(„student.csv‟, „w‟) as writeFile:
import sqlite3 writer = csv.writer(writeFile)
connection = sqlite3.connect("Academy.db") writer.writerows(lines)
cursor = connection.cursor() readFile.close()
writeFile.close()
cursor.execute("SELECT DISTINCT (Grade)
FROM student where gender='M'") 68. Identify the module, operator, definition
result = cursor.fetchall() name for the following
print(*result,sep="\n") welcome.display()
63. Read the following details. Based on that ans:
write a python script to display welcome.display()
department wise records
database name :- organization.db
Function call
Table name :- Employee
Columns in the table :- Eno, EmpName, Dot Operator
Esal, Dept Module Name
Ans: 69. Draw the output for the following data
import sqlite3 visualization plot.
connection=sqlite3.connect(“organization.db”) import matplotlib.pyplot as plt
c=conn.execute(“SELECT *FROM employee plt.bar([1,3,5,7,9],[5,2,7,8,2],label="Example one")
GROUP BY Dept”) plt.bar([2,4,6,8,10],[8,6,2,5,6], label="Example two",
for row in c: color='g')
print(row) plt.legend()
conn.close() plt.xlabel('bar number')
64. Read the following details. Based on that plt.ylabel('bar height')
write a python script to display records in plt.title('Epic Graph\nAnother Line! Whoa')
desending order of plt.show()
Eno Output:
database name :- organization.db
Table name :- Employee
Columns in the table :- Eno, EmpName,
Esal, Dept
Ans:
import sqlite3
connection=sqlite3.connect(“organization.db”)
cursor=conncetion,cursor()
cursor.execute(“SELECT *FROM employee
ORDER BY Eno DESC”)
result=cursor.fetchall()
Print(result)
65. Write a Python program to read a CSV file
with default delimiter comma (,). 70. Write the plot for the following pie chart
import csv output.
with open('c:\pyprg\sample1.csv','r',newline„=‟) as F:
reader = csv.reader(F)
for row in reader:
print(row)
F.close()
66. Write a SQL statement to modify the
student table structure by adding a new
field.
Program:
SQL Statement: import matplotlib.pyplot as plt
ALTER TABLE student ADD address slices=[13,7,2,2]
char(50); labels=["playing","sleeping","eating","working"]
plt.pie(slices,labels=labels,autopct="%.1f")
plt.title("Interesting Graph Check It Out")
plt.show()
Page 10 of 10
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
1. What are called Parameters and write a note 2. Explain with example Pure and impure
on functions.
(i) Parameter without Type Pure Function:
(ii) Parameter with Type Pure functions are functions which will
give exact result when the same
Parameters are the variables in a function arguments are passed.
definition and arguments are the values which For example the mathematical function sin
are passed to a function definition. (0) always results 0.
(i) Parameter without Type This means that every time you call the
function with the same arguments, you will
Let us see an example of a function
always get the same result.
definition: A function can be a pure function provided
(requires: b>=0 ) it should not have any external variable
(returns: a to the power of b) which will alter the behaviour of that
let rec pow a b:= variable.
if b=0 then 1 Let us see an example
else a * pow a (b-1) let square x:=
In the above function definition variable „b‟ is return: x * x
the parameter and the value which is passed The above function square is a pure
to the variable „b‟ is the argument. function because it will not give different
The precondition (requires) and postcondition results for same input.
(returns) of the function is given. Note we Strlen( ) is a pure function
have not mentioned any types: (data types). Evaluation of pure functions does not
Some language compiler solves this type cause any side effects to its output
(data type) inference problem algorithmically, Impure functions:
but some require the type to be mentioned. The variables used inside the function
In the above function definition if expression may cause side effects though the
can return 1 in the then branch, shows that as functions which are not passed with any
per the typing rule the entire if expression has arguments. In such cases the function is
called impure function.
type int.
When a function depends on variables or
„b‟ is compared to 0 with the equality operator, functions outside of its definition block,
so „b‟ is also a type of „int‟. you can never be sure that the function
Since „a‟ is multiplied with another expression will behave the same every time it‟s
using the * operator, „a‟ must be an int. called.
(ii) Parameter with Type For example the mathematical function
Now let us write the same function definition random() will give different outputs for the
with types for some reason: same function call.
(requires: b>=0 ) letrandomnumber :=
(returns: a to the power of b ) a := random()
let rec pow (a: int) (b: int) : int := if a > 10 then
if b=0 then 1 return: a
else a * pow a (b-1) else
When we write the type annotations for „a‟ and return: 10
„b‟ the parentheses are mandatory. Here the function Random is impure as it is
Generally we can leave out these annotations, not sure what will be the result when we
because it's simpler to let the compiler infer call the function.
them. 3. Write any Five Characteristics of Modules.
This is useful on times when you get a type The following are the desirable characteristics of
error from the compiler that doesn't make a module.
sense. 1) Modules contain instructions, processing logic,
Explicitly annotating the types can help with and data.
2) Modules can be separately compiled and
debugging such an error message.
stored in a library.
3) Modules can be included in a program.
4) Module segments can be used by invoking a
name and some parameters.
5) Module segments can be used by other
modules.
Page 1 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
4. Explain with an example interface and 5. What is a List? Why List can be called as
implementation. Pairs. Explain with suitable example
An interface is a set of action that an object List is constructed by placing expressions
can do. within square brackets separated by commas.
For example when you press a light switch, the
light goes on, you may not have cared how it Such an expression is called a list literal. List
splashed the light. can store multiple values.
In Object Oriented Programming language, Each value can be of any type and can even
anInterface is a description of all functions. be another list.
In our example, anything that "ACTS LIKE" a Example for List [10, 20].
light, should have function definitions like The elements of a list can be accessed in two
turn_on ( ) and a turn_off ( ). ways. The first way is via our familiar method
The difference between interface and of multiple assignment, which unpacks a list
implementation is into its elements and binds each element to a
Interface Implementation different name.
Interface just defines Implementation carries lst := [10, 20]
what an object can do, out the instructions x, y := lst
but won‟t actually do it defined in the interface In the above example x will become10 and y
will become 20.
In object oriented programs classes are the The example mentioned above mathematically
interface and how the object is processed and we can represent list similar to a set.
executed is the implementation.
lst[(0, 10), (1, 20)] - where
Page 3 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
8. Discuss about Linear search algorithm. 10. What is Binary search? Discuss with example.
Linear search also called sequential search is a Binary search also called half-interval search
sequential method for finding a particular value algorithm. It finds the position of a search element
in a list. This method checks the search element within a sorted array. The binary search algorithm can
with each element in sequence until the desired be done as divide-and-conquer search algorithm and
element is found or the list is exhausted. In this executes in logarithmic time.
searching algorithm, list need not be ordered. Procedure for Binary search
1) Start with the middle element:
Procedure: If the search element is equal to the middle
1) Traverse the array using for loop element of the array i.e., the middle value =
2) In every iteration, compare the target search number of elements in array/2, then return the
key value with the current value of the list. index of the middle element.
If the values match, display the current If not, then compare the middle element with
index and value of the array the search value,
If the values do not match, move on to the If the search element is greater than the
next array element. number in the middle index, then select the
elements to the right side of the middle index,
3) If no match is found, display the search and go to Step-1.
element not found. If the search element is less than the number
index 0 1 2 3 4 in the middle index, then select the elements
values 10 12 20 25 30 to the left side of the middle index, and start
To search the number 25 in the array given with Step-1.
above, linear search will go step by step in a 2) When a match is found, display success message
sequential order starting from the first element with the index of the element matched.
in the given array. 3) If no match is found for all comparisons, then
if the search element is found that index is display unsuccessful message.
Binary Search Working principles
returned otherwise the search is continued till List of elements in an array must be sorted first for
the last index of the array. Binary search.
In this example number 25 is found at index Let us assume that the search element is 60 and
number 3. we need to search the location or index of search
9. Describe in detail the procedure Script mode element 60 using binary search.
programming.
Script mode Programming:
Basically, a script is a text file containing the Python First, we find index of middle element of the array
statements. by using this formula :
Python Scripts are reusable code. mid=low+(high-low)/2
Once the script is created, it can be executed again Here it is, 0+(9-0)/2=4 (fractional part ignored). So,
and again without retyping. 4 is the mid value of the array.
The Scripts are editable.
(i) Creating Scripts in Python
1) Choose File → New File or press Ctrl + N in
Python shell window.
2) An untitled blank script text editor will be The value stored at location or index 4 is 50. As
displayed on screen as shown. the search value 60 is greater than 50.
3) Type the following code in Script editor Now we change our low to mid + 1 and find the
a =100 new mid value again using the formula.
b = 350 low = mid+1
c = a+b mid = low+(high-low)/2
print ("The Sum=", c) Our new mid is 7 now. We compare the value
(ii) Saving Python Script stored at location 7 with our target value 60 is less
1) Choose File → Save or Press Ctrl + S than 80.
2) Now, Save As dialog box appears on the screen
as shown.
3) In the Save As dialog box, select the location The search element still not found. Hence, we
where you want to save your Python code, and
type the file name in File Name box. Python files calculated the mid again by using the formula.
are by default saved with extension .py. So, the search element must be in the lower part
4) Finally, click Save button to save your Python from the current mid value location.
script. high=mid-1
(iii) Executing Python Script mid=low+(high-low)/2
1) Choose Run → Run Module or Press F5 Now the mid value is 5.
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, Now we compare the value stored at location 5
go back to Script editor, make corrections, save
the file using Ctrl + S or File → Save and execute with our search element. We found that it is a
it again. match.
3) For all error free code, the output will appear in We can conclude that the search element 60 is
the IDLE window of Python as shown. found at location or index 5.
Page 4 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
11. Explain the Bubble sort algorithm with 12. Explain the concept of Dynamic programming
example. with suitable example.
Bubble sort is a simple sorting algorithm. The Dynamic programming is an algorithmic design
algorithm starts at the beginning of the list of method that can be used when the solution to
values stored in an array.
It compares each pair of adjacent elements a problem can be viewed as the result of a
and swaps them if they are in the unsorted sequence of decisions.
order. Dynamic programming approach is similar to
This comparison and passed to be continued divide and conquer.
until no swaps are needed, which indicates The given problem is divided into smaller and
that the list of values stored in an array is yet smaller possible sub-problems.
sorted. The algorithm is a comparison sort, is Dynamic programming is used whenever
named for the way smaller elements "bubble" problems can be divided into similar sub-
to the top of the list. problems.
Although the algorithm is simple, it is too slow
and less efficient when compared to insertion so that their results can be re-used to complete
sort and other sorting methods. the process.
Assume list is an array of n elements. The Dynamic programming approaches are used to
swap function swaps the values of the given find the solution in optimized way.
array elements. The solutions of overlapped sub-problems are
Procedure: combined in order to get the better solution.
1) Start with the first element i.e., index = 0, Steps to do Dynamic programming
compare the current element with the next The given problem will be divided into
element of the array. smaller overlapping sub-problems.
2) If the current element is greater than the next
element of the array, swap them. An optimum solution for the given problem
3) If the current element is less than the next or can be achieved by using result of smaller
right side of the element, move to the next sub-problem.
element. Go to Step 1 and repeat until end of Dynamic algorithms uses Memoization.
the index is reached. Fibonacci Iterative Algorithm with Dynamic
Let's consider an array with values {15, 11, programming approach
16, 12, 14, 13} Below, we have a pictorial The following example shows a simple
representation of how bubble sort will sort Dynamic programming approach for the
the given array. generation of Fibonacci series.
Initialize f0=0, f1 =1
step-1: Print the initial values of Fibonacci f0
and f1
step-2: Calculate fibanocci fib ← f0 + f1
step-3: Assign f0← f1, f1← fib
step-4: Print the next consecutive value of
fibanocci fib
step-5: Goto step-2 and repeat until the specified
number of terms generated
For example if we generate fibobnacci series
upto 10 digits, the algorithm will generate the
series as shown below:
The Fibonacci series is : 0 1 1 2 3 5 8 13 21
34 55
Page 5 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
13. Explain input() and print() functions with 14. Discuss in detail about Tokens in Python
examples. Python breaks each logical line into a
1) print() function sequence of elementary lexical
In Python, the print( ) function is used to components known as Tokens. The normal
display result on the screen. The syntax for token types are
print( ) is as follows: 1) Identifiers,
2) Keywords,
Example – 1:
3) Operators,
print (“string to be displayed as output ” ) 4) Delimiters and
print (variable ) 5) Literals.
print (“String to be displayed as output ”, Whitespace separation is necessary
variable) between tokens.
print (“String1 ”, variable, “String 2”, variable, 1) Identifiers :
“String 3” ……) An Identifier is a name used to identify a
Example – 2: variable, function, class, module or object.
>>>print(“Welcome to Python Programming”) Example of valid identifiers
Welcome to Python Programming Sum, total_marks, regno, num1
>>> x = 5 Example of invalid identifiers
>>> y = 6 12Name, name$, total-mark, continue
>>> z = x + y 2) Keywords :
>>> print (“The sum = ”, z) Keywords are special words used by
The sum = 11 Python interpreter to recognize the
The print( ) evaluates the expression before structure of program.
printing it on the monitor. As these words have specific meaning for
The print( ) displays an entire statement interpreter, they cannot be used for any
other purpose.
which is specified within print( ).
False class finally is return
Comma( , ) is used as a separator in print
None continue for lambda try
( ) to print more than one item.
3) Operators
2) input() function In computer programming languages
In Python, input( ) function is used to accept operators are special symbols which
data as input at run time. The syntax for represent computations, conditional
input() function is, matching etc.
Variable = input (“prompt string”) The value of an operator used is called
If a prompt string is used, it is displayed on operands.
the monitor; the user can provide expected Operators are categorized as Arithmetic,
data from the input device. Relational, Logical, Assignment etc. Value
The input( ) takes whatever is typed from the and variables when used with operator are
keyboard and stores the entered data in the known as operands.
given variable. 4) Delimiters
If prompt string is not given in input( ) no Delimiters are sequence of one or more
message is displayed on the screen, thus, characters used to specify the boundary
the user will not know what is to be typed as between seperate, independent regions in
input. plain text or other data streams.
Example 1:input( ) with prompt string Python uses the symbols and symbol
>>> city=input (“Enter Your City: ”) combinations as delimiters in expressions,
Enter Your City: Madurai lists, dictionaries and strings. Following are
the delimiters.
>>> print (“I am from “, city)
( ) [ ] { }
I am from Madurai
, : . „ = ;
The input ( ) accepts all data as string but not 5) Literals
as numbers. If a numerical value is entered, Literal is a raw data given to a variable or
the input values should be explicitly constant. In Python, there are various
converted into numeric data type. types of literals.
The int( ) function is used to convert string 1) Numeric 2) String 3) Boolean
data as integer data explicitly. Escape Sequences
Example 2: In Python strings, the backslash "\" is a
x = int (input(“Enter Number 1: ”)) special character, also called the "escape"
y = int (input(“Enter Number 2: ”)) character.
print (“The sum = ”, x+y) It is used in representing certain
Output: whitespace characters: "\t" is a tab, "\n" is a
Enter Number 1: 34 newline.
Enter Number 2: 56 For example
The sum = 90 >>> print ("It\'s rainning")
It's raining
Page 6 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
15. Write a detail note on for loop 16. Write a detail note on if..else..elif
The for loop is usually known as a definite statement with suitable example.
loop, because the programmer knows When we need to construct a chain of if
exactly how many times the loop will be statement(s) then „elif‟ clause can be used
executed. instead of „if else‟.
Syntax: Syntax:
forcounter_variable in sequence: if<condition-1>:
statements-block 1 statements-block 1
[else: # optional block elif<condition-2>:
statements-block 2] statements-block 2
The for ....in statement is a looping else:
statement used in Python to iterate over a statements-block n
sequence of objects, i.e., it goes through In the syntax of if..elif..elsementioned
each item in a sequence. above, condition-1 is tested if it is true then
Here the sequence is the collection of statements-block1 is executed, otherwise
ordered or unordered values or even a the control checks condition-2, if it is true
string. statements-block2 is executed and even if
The control variable accesses each item of it fails statements-block n mentioned in
the sequence on each iteration until it else part is executed.
reaches the last item in the sequence. „Multiple if..elsestatements can be
The range( ) is a built-in function, to combined to one if..elif…else.
generate series of values between two „elif‟ can be considered to be abbreviation
numeric intervals. of „else if‟.
The syntax of range( ) is as follows: In an „if‟ statement there is no limit of „elif‟
range (start,stop,[step]) clause that can be used, but an „else‟
Where, clause if used should be placed at the end.
start – refers to the initial value Example:
stop – refers to the final value n1=int (input(“Enter the first number : ”))
step – refers to increment value, this is n2=int (input(“Enter the second number: ”))
optional part. n3=int (input(“Enter the third number: ”))
Ex: range (1,30,1) - will start the range of ifn1>=n2 and n1>=n3:
values from 1 and end at 29 print (“n1 is greater then n2,n3”)
if n1>=n2 and n1>=n3:
print (“n2 is greater then n1,n3”)
else:
print (“n3 is greater then n1,n2”)
Output 1:
Enter the first number :35
Enter the second number : 30
Enter the third number : 25
n1 is greater then n2,n3
EX:
for i in range (2,10,2):
print (i, end=' ')
Output:
2468
Page 7 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
17. Explain the scope of variables with an 18. Explain recursive function with an
example. example.
Scope of variable refers to the part of the When a function calls itself is known as
program, where it is accessible, i.e., area recursion. Recursion works like loop but
where you can refer (use) it. sometimes it makes more sense to use
We can say that scope holds the current recursion than loop. You can convert any
loop to recursion.
set of variables and their values.
A recursive function calls itself.
We will study two types of scopes - local Imagine a process would iterate indefinitely
scope and global scope. if not stopped by some condition! Such a
1) Local Scope process is known as infinite iteration.
A variable declared inside the function's The condition that is applied in any
body is known as local variable. recursive function is known as base
Rules of local variable condition.
1) A variable with local scope can be A base condition is must in every recursive
accessed only within the function function otherwise it will continue to
that it is created in. execute like an infinite loop.
2) When a variable is created inside Overview of how recursive function works
the function the variable becomes 1) Recursive function is called by some
local to it. external code.
3) A local variable only exists while 2) If the base condition is met then the
the function is executing. program gives meaningful output and
4) The formal parameters are also exits.
local to function. 3) Otherwise, function does some required
Example: processing and then calls itself to
continue recursion.
defloc():
Example:
y=0 # local scope def fact(n):
print(y) if n == 0:
loc() return 1
Output: else:
0 return n * fact (n-1)
2) Global Scope print (fact (0))
A variable, with global scope can be used print (fact (5))
anywhere in the program. It can be Output:
created by defining a variable outside the 1
scope of any function. 120
Rules of global Keyword
1) When we define a variable outside a
function, it‟s global by default. You
don‟t have to use global keyword.
2) We use global keyword to modify
the value of the global variable
inside a function.
3) Use of global keyword outside a
function has no effect
Example:
x = 0 # global variable
def add():
global x
x = x + 5 # increment by 5
print ("Inside add() function x
value is :", x)
add()
print ("In main x value is :", x)
Output:
Inside add() function x value is : 5
In main x value is : 5
Page 8 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
19. Explain the different types of function with 3) built-in functions
an example. There are many built-in functions that
User defined function comes with the language python (for
you can define your own function. When instance, the print() function)
defining functions there are multiple things 4) Recursive function:
that need to be noted; When a function calls itself is known as
Function blocks begin with the recursion. Recursion works like loop but
keyword “def” followed by function sometimes it makes more sense to use
name and parenthesis(). recursion than loop. You can convert any
If any input parameters are present loop to recursion.
should be placed within these Example:
parentheses when you define a def fact(n):
function. if n == 0:
The code block always comes after a return 1
colon (:) and is indented. else:
The statement “return [expression]” return n * fact (n-1)
exits a function, optionally passing print (fact (0))
back an expression to the caller. A print (fact (5))
“return” with no arguments is the same Output:
as return None. 1
Syntax for User defined function 120
def<function_name ([parameter1,
parameter2…] )> :
<Block of Statements>
return<expression / None>
Example:
def hello():
print (“hello - Python”)
return
hello()
Output:
hello-python
2) lambda or anonymous function
In Python, anonymous function is a
function that is defined without a name.
While normal functions are defined using
the defkeyword, in Python anonymous
functions are defined using the lambda
keyword. Hence, anonymous functions are
also called as lambda functions.
The syntax for anonymous:
lambda [argument(s)] :expression
Example:
sum = lambda arg1, arg2: arg1 + arg2
print ('The Sum is :', sum(30,40))
print ('The Sum is :', sum(-30,40))
Output:
The Sum is : 70
The Sum is : 10
Page 9 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
20. Explain the following built-in functions.
(a) id()
(b) chr()
(c) round()
(d) type()
(e) pow()
Function Description Syntax Example
x=15
Return the “identity” of an y='a'
object. i.e. the address of print ('address of x is :',id (x))
the object in memory. print ('address of y is :',id (y))
id() id (object)
Note: the address of x and y Output:
may differ in your system. address of x is : 1357486752
address of y is : 13480736
c=65
Returns the Unicode d=43
character for the given print (chr (c))
ASCII value. chr (i) prin t(chr (d))
chr()
This function is inverse of Output:
ord() function. A
+
Returns the nearest integer
to its input.
1. First argument (number)
x= 17.9
is used to specify the
print ('x value is rounded to',round (x))
value to be rounded.
round() round (number [,ndigits])
2. Second argument
Output:
(ndigits) is used to specify
x value is rounded to 18
the number of decimal
digits desired after
rounding.
Returns the type of object
x= 15.2
for the given single object.
print (type (x))
type() type (object)
Note: This function used
Output:
with single object
<class 'float'>
parameter.
a= 5
b=2
Returns the computation of
print (pow (a,b))
pow() ab i.e. (a**b ) a raised to the pow (a,b)
power of b.
Output:
25
Page 10 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
21. Explain about string operators in python 22. What the different ways to insert an
with suitable example. element in a list. Explain with suitable
Python provides the following operators for example.
string operations. These operators are useful There are threeways are used to insert
to manipulate string. elements in a list.
i) Concatenation (+)
Joining of two or more strings is called as 1) append() function is used to add a single
Concatenation. The plus (+) operator is used element. Syntax:
to concatenate strings in python.Example: List.append (element to be added)
>>> "welcome" + "Python" Example:
'welcomePython' >>>Mylist=[34, 45, 48]
ii) Append (+ =) >>>Mylist.append(90)
Adding more strings at the end of an existing >>>print(Mylist)
string is known as append. The operator += Output:
is used to append a new string with an [34, 45, 48, 90]
existing string.
Example: In the above example, Through
>>> str1="Welcome to " >>>Mylist.append(90) statement, an
>>>str1+="Learn Python" additional value 90 is included with the
>>> print (str1) existing list as last element.
Welcome to Learn Python 2) extend() function is used to add more than
iii) Repeating (*) one element to an existing list.Syntax:
The multiplication operator (*) is used to List.extend( [elements to be added])
display a string in multiple number of times. Example:
Example: >>>Mylist=[34, 45, 48]
>>> str1="Welcome "
>>> print (str1*4) >>>Mylist.extend([71, 32, 29])
Welcome WelcomeWelcomeWelcome >>>print(Mylist)
iv) String slicing Output:
Slice is a substring of a main string. A [34, 45, 48, 90, 71, 32, 29]
substring can be taken from the original In the above code, extend() function is
string by using [ ] operator and index or used to include multiple elements.
subscript values. Thus, [ ] is also known as 3) insert() function is used to insert an
slicing operator. Using slice operator, you element at any position of a list.If you want
have to slice one or more substrings from a to include an element at your desired
main string.
General format of slice operation: position, you can use insert () function.
str[start:end] Syntax:
Where start is the beginning index and end List.insert (position index, element)
is the last index value of a character in the Example:
string. Python takes the end value less than >>>MyList=[34,98,47,'Kannan',
one from the actual index specified. 'Gowrisankar', 'Lenin', 'Sreenivasan' ]
Example: >>>MyList.insert(3, 'Ramakrishnan')
>>> str1="THIRUKKURAL" >>>print(MyList)
>>> print (str1[0:5]) Output:
THIRU [34, 98, 47, 'Ramakrishnan', 'Kannan',
v) Stride when slicing string
'Gowrisankar', 'Lenin', 'Sreenivasan']
When the slicing operation, you can specify
a third argument as the stride, which refers
to the number of characters to move forward
after the first character is retrieved from the
string. The default value of stride is 1.
Example:
>>> str1 = "Welcome to learn Python"
>>>print (str1[10:16:2])
er
Page 11 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
23. Explain the different set operations
supported by python with suitable
example.
As you learnt in mathematics, the python is 3) Difference:It includes all elements that are in
also supports the set operations such as first set (say set A) but not in the second set
Union, Intersection, difference and Symmetric (say set B).
difference.
1) Union: It includes all elements from two or
more sets.
The operator & is used to intersect two The caret (^) operator is used to symmetric
sets in python. The function difference set operation in python. The
intersection() is also used to intersect function symmetric_difference() is also
two sets in python. used to do the same operation.
Example: Program to insect two sets Example: Program to symmetric difference
using intersection operator of two sets using caret operator
set_A={10,20,30,40,‟A‟,‟C‟} set_A={10,20,30,40,‟A‟,‟C‟}
set_B={20,40,50,60,‟A‟,‟B‟} set_B={20,40,50,60,‟A‟,‟B‟}
print(set_A&set_B) print(set_A ^ set_B)
Output: Output:
{20,40,'A'} {10,30,50,60,‟B‟,‟C‟}
Page 12 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
24. What is the purpose of range()? Explain 26. Explain about constructor and destructor
with an example. with suitable example.
The range() is a function used to generate a 1) Constructor is the special function that is
series of values in Python. Using range() automatically executed when an object of a
function, you can create list with series of class is created. In Python, there is a
values. The range() function has three special function called “init” which act as a
arguments. Constructor. It must begin and end with
Syntax of range ( ) function: double underscore.
range (start value, end value, step value) This method is used to initialize the class
where, variables.
start value – beginning value of series. General format of _ _init_ _(method
Zero is the default beginning value. (Constructor function)
end value – upper limit of series. Python def _ _init_ _(self, [args ……..]):
takes the ending value as upper limit – 1. <statements>
step value – It is an optional argument, Example:
which is used to generate different interval class Sample:
of values. def __init__(self, num):
Example: Generating first 10 even numbers print("Constructor of class
for x in range (2, 11, 2): Sample...")
print(x) self.num=num Instance variable
Output: print("The value is :", num)
2 S=Sample(10)
4 output.
6 Constructor of class Sample...
8 The value is : 10
10 2) Destructor is also a special method to
Creating a list with series of values:Using the destroy the objects. In Python, _ _del_ _( )
range() function, you can create a list with method is used as destructor. It is just
series of values. To convert the result of opposite to constructor.
range() function into list, we need one more Example:
function called list(). The list()function makes class Sample:
the result of range() as a list. num=0
Syntax: def __init__(self, var):
List_Varibale = list ( range ( ) ) Sample.num+=1
Example: self.var=var
>>>Even_List = list(range(2,11,2)) print("The object value is = ",
>>>print(Even_List) self.var)
Output: print("The value of class variable
[2, 4, 6, 8, 10] is= ", Sample.num)
Even_List list has the elements of first five def __del__(self):
even numbers. Sample.num-=1
25. What is nested tuple? Explain with an print("Object with value %d is
example. exit from the scope"%self.var)
In Python, a tuple can be defined inside S1=Sample(15)
another tuple; called Nested tuple. S2=Sample(35)
In a nested tuple, each tuple is considered S3=Sample(45)
as an element. del S1, S2, S3
The for loop will be useful to access all the Output:
elements in a nested tuple. The object value is = 15
Example: The value of class variable is = 1
Toppers = (("Vinodini", "XII-F", 98.7), The object value is = 35
("Soundarya", "XII-H", 97.5), The value of class variable is = 2
("Tharani", "XII-F", 95.3), The object value is = 45
("Saisri", "XII-G", 93.8)) The value of class variable is = 3
for i in Toppers: Object with value 15 is exit from the scope
print(i) Object with value 35 is exit from the scope
Output: Object with value 45 is exit from the scope
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F', 95.3)
('Saisri', 'XII-G', 93.8)
Page 13 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
27. Explain the different types of data model.
Following are the different types of a Data
Model
1) Hierarchical Model 2) Relational Model
3) Network Database Model
4) Entity Relationship Model 5) Object Model
1) Hierarchical Model
Hierarchical model was developed by IBM
as Information Management System.
In Hierarchical model, data is represented
as a simple tree like structure form.
This model represents a one-to-many
relationship i.e parent-child relationship. 4) Entity Relationship Model. (ER model)
One child can have only one parent but In this database model, relationship are
one parent can have many children. created by dividing the object into entity
This model is mainly used in IBM Main and its characteristics into attributes.
Frame computers. It was developed by Chen in 1976.
This model is useful in developing a
conceptual design for the database.
The developer can easily understand the
system by looking at ER model
constructed.
Rectangle represents the entities.
E.g. Doctor and Patient
Ellipse represents the attributes
E.g. D-id, D-name, P-id, P-name.
Diamond represents the relationship in
ER diagrams
2) Relational Model E.g. Doctor diagnosis the Patient
The Relational Database model was first
proposed by E.F. Codd in 1970 .
Nowadays, it is the most widespread data
model used for database applications
around the world.
The basic structure of data in relational
model is tables (relations). 5) Object Model
All the information‟s related to a particular Object model stores the data in the form
type is stored in rows of that table. of objects, attributes and methods,
Hence tables are also known as relations classes and Inheritance.
in a relational model. This model handles more complex
A relation key is an attribute which applications, such as Geographic
uniquely identifies a particular tuple information System (GIS), scientific
experiments, engineering design and
manufacturing.
It is used in file Management System. It
represents real world objects, attributes
and behaviors.
3) Network Model
Network database model is an extended
form of hierarchical data model.
In a Network model, a child may have
many parent nodes. It represents the data Circle has the attribute radius.
in many-to-many relationships. Rectangle has the attributes length and
This model is easier and faster to access breadth.
the data. The objects Circle, Rectangle and
Triangle inherit from the object Shape.
Page 14 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
28. Explain the different types of relationship
mapping.
Following are the types of relationships used 3) Many-to-One Relationship
in a database. In Many-to-One Relationship, many
1) One-to-One Relationship entities can be related with only one in
2) One-to-Many Relationship the other entity.
3) Many-to-One Relationship For example: A number of staff
4) Many-to-Many Relationship members working in one Department.
Multiple rows in staff members table is
1) One-to-One Relationship related with only one row in Department
In One-to-One Relationship, one entity is table.
related with only one other entity.
One row in a table is linked with only
one row in another table and vice versa.
For example: A student can have only
one exam number
4) Many-to-Many Relationship
A many-to-many relationship occurs
2) One-to-Many Relationship when multiple records in a table are
In One-to-Many relationship, one entity associated with multiple records in
is related to many other entities. another table.
One row in a table A is linked to many Example: Books and Student.Many
rows in a table B, but one row in a table Books in a Library are issued to many
B is linked to only one row in table A. students.
For example: One Department has
many staff members.
Page 15 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
29. Explain the different operators in Relational
algebra with suitable examples. Table A ∪B
Relational Algebra is divided into various groups
1) Unary Relational Operations Studno Name
SELECT ( symbol : σ)
PROJECT ( symbol : Π) cs1 Kannan
2) Relational Algebra Operations from Set Theory cs2 GowriShankar
UNION (∪)
INTERSECTION (∩) cs3 Lenin
DIFFERENCE (−) cs4 Padmaja
CARTESIAN PRODUCT (X)
SELECT (symbol : σ) SET DIFFERENCE ( Symbol : - )
General form σc( R ) with a relation R and a The result of A – B, is a relation which
condition C on the attributes of R. includes all tuples that are in A but not in B.
The SELECT operation is used for selecting The attribute name of A has to match with the
a subset with tuples according to a given attribute name in B.
condition. Example 4 ( using Table 2) : Result
Select filters out all tuples that do not satisfy Table A - B
C.
cs4 Padmaja
STUDENT
INTERSECTION (symbol : ∩) A ∩ B
Studno Name Course Year Defines a relation consisting of a set of all
cs1 Kannan Big Data II tuple that are in both in A and B. However, A
and B must be union-compatible.
cs2 Gowri Shankar R language I Example 5 (using Table 2)
cs3 Lenin Big Data I A∩B
Python cs1 Kannan
cs4 Padmaja I
Programming
Table 1 cs3 Lenin
“Big Data” (STUDENT ) PRODUCT OR CARTESIAN PRODUCT
course (Symbol : X )
Studno Name Course Year Cross product is a way of combining two
relations. The resulting relation contains,
cs1 Kannan Big Data II both relations being combined.
cs3 Lenin Big Data I A x B means A times B, where the relation A
and B have different attributes.
PROJECT (symbol : Π) This type of operation is helpful to merge
The projection eliminates all attributes of the columns from two relations.
input relation but those mentioned in the Example:
projection list. The projection method
defines a relation that contains a vertical Table A Table B
subset of Relation. Studno name course subject
Example 1 using Table 1
course(STUDENT)
cs1 Kannan cs28 Big Data
python
cs4 Padmaja cs25
programming
Course Cartesian product :
Big Data Table A = 2
Table B = 2
R language Table A x B = 2 X 2=4
Python Programming studno name Course subject
UNION (Symbol :∪) cs1 Kannan cs28 Big Data
It includes all tuples that are in tables A or in
B. It also eliminates duplicates. Set A Union python
cs1 Kannan cs25
rogramming
Set B would be expressed as A ∪ B
Example 3: Consider the following tables cs4 Padmaja cs28 Big Data
Table A Table B python
cs4 Padmaja cs25
programming
Studno Name Studno Name
cs1 Kannan cs1 Kannan
cs3 Lenin cs2 GowriShankarn
cs4 Padmaja cs3 Lenin
Table 2
Page 16 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
Page 17 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
32. Write the different types of constraints and 3) DEFAULT Constraint
their functions. The DEFAULT constraint is used to assign
Constraints ensure database integrity, therefore a default value for the field. When no value
known as database integrity constraints. The is given for the specified field having
different types of constraints are : DEFAULT constraint, automatically the
1) Unique Constraint default value will be assigned to the field.
2) Primary Key Constraint CREATE TABLE Student
3) Default Constraint (
4) Check Constraint Admno integer PRIMARY KEY,
5) Table Constraint Name char(20)NOT NULL,
1) Unique Constraint Gender char(1),
This constraint ensures that no two rows Age integer DEFAULT 17, → Default
have the same value in the specified Constraint
columns. Place char(10)
For example UNIQUE constraint applied on );
Admno of student table ensures that no two In the above example when no value is
students have the same admission number entered in age by the user, it automatically
and the constraint can be used as: assigns 17 to Age.
CREATE TABLE Student 4) Check Constraint
( This constraint helps to set a limit value
Admno integer NOT NULL UNIQUE, → placed for a field. When we define a check
Unique constraint constraint on a single column, it allows only
Name char (20) NOT NULL, the restricted values on that field.
Gender char (1), Example:
Age integer, CREATE TABLE Student
Place char (10), (
); Admno integer PRIMARY KEY
The UNIQUE constraint can be applied only Name char(20)NOT NULL,
to fields that have also been declared as Gender char(1),
NOT NULL. Age integer CHECK (Age <=19), →
2) Primary Key Constraint Check Constraint
This constraint declares a field as a Primary Place char(10),
key which helps to uniquely identify a );
record. In the above example the value of Age must
It is similar to unique constraint except that be less than or equal to 19.
only one field of a table can be set as 5) TABLE CONSTRAINT
primary key. The primary key does not allow When the constraint is applied to a group of
NULL values. fields of the table, it is known as Table
Example showing Primary Key Constraint in constraint.
the student table: The table constraint is normally given at the
CREATE TABLE Student end of the table definition.
( Let us take a new table namely Student1
Admno integer PRIMARY KEY, → with the following fields Admno, Firstname,
Primary Key constraint Lastname, Gender, Age, Place:
Name char(20) NOT NULL, CREATE TABLE Student 1
Gender char(1), (
Age integer, Admno integer NOT NULL,
Place char(10), Firstnamechar(20),
); Lastnamechar(20),
Gender char(1),
Age integer,
Place char(10),
PRIMARY KEY (Firstname, Lastname) →
Table constraint
);
In the above example, the two fields,
Firstname and Lastname are defined as
Primary key which is a Table constraint.
Page 18 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
33. What are the components of SQL? Write the 4) TRANSACTIONAL CONTROL LANGUAGE
commands in each. Transactional control language (TCL)
SQL commands are divided into five categories: commands are used to manage
1) DML - Data Manipulation Language transactions in the database.
2) DDL - Data Definition Language These are used to manage the changes
3) DCL - Data Control Language made to the data in a table by DML
4) TCL - Transactional Control Language statements.
5) DQL - Data Query Language SQL command which come under Transfer
1) DATA MANIPULATION LANGUAGE Control Language are:
A Data Manipulation Language (DML) is a Commit Saves any transaction into the
query language used for adding (inserting), database permanently.
removing (deleting), and modifying Roll back Restores the database to last
(updating) data in a database. commit state.
In SQL, the data manipulation language Save point Temporarily save a transaction so
comprises the SQL-data change that you can rollback.
statements, which modify stored data but 5) DATA QUERY LANGUAGE
not the schema of the database table. The Data Query Language consist of
SQL commands which comes under Data commands used to query or retrieve data
Manipulation Language are : from a database. One such SQL command
Insert Inserts data into a table in Data Query Language is
Update Updates the existing data within a Select : It displays the records from the
table. table.
Delete Deletes all records from a table, but 34. Differentiate Excel file and CSV file.
not the space occupied by them. Excel CSV
2) DATA DEFINITION LANGUAGE
The Data Definition Language (DDL) Excel is a binary file CSV format is a plain
consist of SQL statements used to define that holds information text format with a
the database structure or schema. about all the series of values
It simply deals with descriptions of the worksheets in a file, separated by commas.
database schema and is used to create
including both content
and modify the structure of database
objects in databases. and formatting.
SQL commands which comes under Data
XLS files can only be CSV can be opened
Definition Language are:
read by applications with any text editor in
Create To create tables in the database.
that have been Windows like notepad,
Alter Alters the structure of the database. especially written to MS Excel, OpenOffice,
Drop Delete tables from database. read their format, and etc.
can only be written in
Truncate Remove all records from a table, the same way.
also release the space occupied by
those records. Excel is a spreadsheet CSV is a format for
3) DATA CONTROL LANGUAGE that saves files into its saving tabular
A Data Control Language (DCL) is a own proprietary format information into a
programming language used to control the viz. xls or xlsx delimited text file with
access of data stored in a database. extension .csv
It is used for controlling privileges in the
database (Authorization). Excel consumes more Importing CSV files
The privileges are required for performing memory while can be much faster,
all the database operations such as importing data and it also consumes
creating sequences, views of tables etc. less memory
SQL commands which come under Data
Control Language are:
Grant Grants permission to one or more
users to perform specific tasks.
Revoke Withdraws the access permission
given by the GRANT statement.
Page 19 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
35. Tabulate the different mode with its 37. Write the rules to be followed to format the
meaning. data in a CSV file.
1) Each record (row of data) is to be located on a
Mode Description separate line, delimited by a line break by
'r' Open a file for reading. (default) pressing enter key.
'w' Open a file for writing. Creates a new For example:
file if it does not exist or truncates the xxx,yyy
file if it exists. denotes enter Key to be pressed
2) The last record in the file may or may not have
'x' Open a file for exclusive creation. If the an ending line break. For example:
file already exists, the operation fails. ppp, qqq
'a' Open for appending at the end of the yyy, xxx
file without truncating it. Creates a new 3) There may be an optional header line
appearing as the first line of the file with the
file if it does not exist. same format as normal record lines. The
't' Open in text mode. (default) header will contain names corresponding to
'b' Open in binary mode. the fields in the file and should contain the
'+' Open a file for updating (reading and same number of fields as the records in the
rest of the file. For example:
writing) field_name1,field_name2,field_name3
36. Write the different methods to read a File aaa,bbb,ccc
in Python. zzz,yyy,xxx CRLF(Carriage Return and Line
There are two ways to read a CSV file. feed)
1. Use the csv module‟s reader function 4) Within the header and each record, there may
2. Use the DictReader class. be one or more fields, separated by commas.
1. Use the csv module‟s reader function Spaces are considered part of a field and
The reader function is designed to take each should not be ignored. The last field in the
line of the file and make a list of all columns. record must not be followed by a comma. For
Using this function one can read data from csv example: Red , Blue
files of different formats like quotes (" "), pipe 5) Each field may or may not be enclosed in
(|) and comma (,). double quotes. If fields are not enclosed with
csv.reader() work with list/tuple. double quotes, then double quotes may not
The syntax for csv.reader() is appear inside the fields. For example:
csv.reader(fileobject,delimiter,fmtparams) "Red","Blue","Green"
where #Field data with doule quotes
file object: passes the path and the mode of Black,White,Yellow
the file #Field data without doule quotes
delimiter : an optional parameter containing the 6) Fields containing line breaks (CRLF), double
standard dilects like , | etc can be quotes, and commas should be enclosed in
omitted double-quotes. For example:
fmtparams: optional parameter which help to Red, “,”, Blue CRLF
override the default values of the # comma itself is a field value.so it is
dialects like enclosed with double quotes
skipinitialspace,quoting etc. Can Red, Blue , Green
be omitted 7) If double-quotes are used to enclose fields,
Example: then a double-quote appearing inside a field
import csv must be preceded with another double quote.
with open('c:\pyprg\sample1.csv','r',newline„=‟) as F: For example:
reader = csv.reader(F) ““Red””, ““Blue””, ““Green”” CRLF
for row in reader:
print(row) # since double quotes is a field value it is
F.close() enclosed with another double quotes
2. Use the DictReader class. , , White
To read a CSV file into a dictionary can be 38. Write any 5 features of Python.
1) Python uses Automatic Garbage Collection
done by using DictReader method of csv whereas C++ does not.
module which creates an object which maps 2) C++ is a statically typed language, while Python
data to a dictionary. is a dynamically typed language.
DictReader works by reading the first line of 3) Python runs through an interpreter, while C++ is
the CSV and using each comma separated pre-compiled.
value in this line as a dictionary key. 4) Python code tends to be 5 to 10 times shorter
csv.DictReader() work with dictionary. than that written in C++.
Example: 5) In Python, there is no need to declare types
import csv explicitly where as it should be done in C++
filename = „c:\pyprg\sample8.csv‟ 6) In Python, a function may accept an argument of
input_file =csv.DictReader(open(filename,‟r‟)) any type, and return multiple values without any
for row in input_file: kind of declaration beforehand. Whereas in C++
print(dict(row)) return statement can return only one value.
Page 20 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
39. Write the syntax for getopt() and explain 40. Write in brief about SQLite and the steps
its arguments and return values used to use it.
Python getopt module 1. SQLite is a simple relational database
The getopt module of Python helps you system, which saves its data in regular
to parse (split) command-line options data files within internal memory of the
and arguments. This module provides computer.
getopt() method to enable command-line 2. Advantages:
argument parsing. It is designed to be embedded in
getopt.getopt function applications, instead of using a
This function parses command-line separate database server program
options and parameter list. Following is such as MySQLor Oracle.
the syntax for this method – SQLite is fast, rigorously tested, and
<opts>,<args>=getopt.getopt(argv, flexible, making it easier to work.
options, [long_options]) Python has a native library for SQLite.
Here is the detail of the parameters − 3. Steps to use SqLite:
1) argv − This is the argument list of Step 1 import sqlite3
values to be parsed (splited). In our Step 2 create a connection using connect ()
program the complete command will method and pass the name of the
be passed as a list. For example database File
2) c:\pyprg\pali.py -i c:\pyprg\pali_cpp Step 3 Set the cursor object cursor =
connection. cursor ()
3) options − This is string of option letters
Connecting to a database in step2
that the Python program recognize as, means passing the name of the
for input or for output, with options (like database to be accessed. If the
„i‟ or „o‟) that followed by a colon (:). database already exists the connection
Here colon is used to denote the will open the same. Otherwise, Python
mode. will open a new database file with the
4) long_options −This contains a list of specified name.
strings. Argument of Long options Cursor in step 3: is a control structure
should be followed by an equal sign used to traverse and fetch the records
of the database.
'='. In our program the C++ file name
Cursor has a major role in working with
along with its path will be passed as Python. All the commands will be
string and „i‟ i will be also passed to executed using cursor object only.
indicate it as the input file. 4. Example:
getopt() method returns value consisting import sqlite3
of two elements. Each of these values connection=sqlite3.connect("Academy.db")
are stored separately in two different list cursor = connection.cursor()
(arrays) opts and args . 5. Execution:
Example: For executing the command use the
opts,args=getopt.getopt(argv,"i:",['ifile=']) cursor method and pass the required
where opts contains [('-i', sql command as a parameter.
'c:\\pyprg\\p4')] Many number of commands can be
-i :- option - mode should be stored in the sql_comm and can be
followed by : (colon) executed one after other.
'c:\\pyprg\\p4' value - absolute path of Any changes made in the values of the
C++ file. record should be saved by the
In our examples since the entire commend "Commit" before closing the
command line commands are parsed "Table connection".
and no leftover argument, the second
argument args will be empty []. If args is
displayed using print() command it
displays the output as [].
>>>print(args)
[]
Page 21 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
41. What is the purpose of sys,os,getopt where each argument contains
module in Python.Explain os.system : function system() defined in os
1) Python‟s sys module: module to interact with the operating
This module provides access to builtin system
g++ : General compiler to compile C++
variables used by the interpreter. One
program under Windows Operating
among the variable in sys module is system.
argv. variable_name1: Name of the C++ file along with its
sys.argv is the list of command-line path and without extension in string
arguments passed to the Python format
program. mode : To specify input or output mode. Here
argv contains all the items that come via it is o prefixed with hyphen.
the command-line input, it's basically a variable_name2: Name of the executable file without
list holding the command-line arguments extension in string format
of the program. For example :
To use sys.argv, import sys should be os.system('g++ ' + cpp_file + ' -o ' + exe_file)
used. 3) Python getopt module:
The first argument, sys.argv[0] contains The getopt module of Python helps you
the name of the python program to parse (split) command-line options
(example pali.py) and arguments. This module provides
and sys.argv [1]is the next argument getopt() method to enable command-line
passed to the program (here it is the argument parsing.
C++ file), which will be the argument getopt.getopt function
passed through main ( ). This function parses command-line
For example options and parameter list. Following is
main(sys.argv[1]) the syntax for this method –
2) Python's OS Module: <opts>,<args>=getopt.getopt(argv,
The OS module in Python provides a options, [long_options])
way of using operating system Here is the detail of the parameters −
dependent functionality. 1) argv − This is the argument list of
The functions that the OS module allows values to be parsed (splited). In our
you to interface with the Windows program the complete command will
operating system where Python is be passed as a list. For example
running on. 2) c:\pyprg\pali.py -i c:\pyprg\pali_cpp
os.system(): Execute the C++ compiling 3) options − This is string of option letters
command (a string contains Unix, C that the Python program recognize as,
command which also supports C++ for input or for output, with options (like
command) in the shell (Here it is „i‟ or „o‟) that followed by a colon (:).
Command Window). Here colon is used to denote the
For Example to compile C++ program mode.
g++ compiler should be invoked. 4) long_options −This contains a list of
To do so the following command is strings. Argument of Long options
used. should be followed by an equal sign
os.system („g++ ‟ + <variable_name1> '='. In our program the C++ file name
+„ -<mode> ‟ + <variable_name2>) along with its path will be passed as
string and „i‟ i will be also passed to
indicate it as the input file.
getopt() method returns value consisting
of two elements. Each of these values
are stored separately in two different list
(arrays) opts and args .
Example:
opts,args=getopt.getopt(argv,"i:",['ifile='])
Page 22 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
42. That is the use of HAVING clause. Give an 44. Explain the various buttons in a matplotlib
example python script window.
Having clause is used to filter data based Buttons in the output:
on the group functions. In the output figure, you can see few buttons
This is similar to WHERE condition but at the bottom left corner. Let us see the use
can be used only with group functions. of these buttons.
Group functions cannot be used in
WHERE Clause but can be used in
HAVING clause.
Example:
Import sqlite3
connection=sqlite3.connect("Academy.db") 1) Home Button:
cursor = connection.cursor() The Home Button will help once you have
cursor.execute("SELECT GENDER, COUNT begun navigating your chart. If you ever
(GENDER) FROM Student GROUP BY
want to return back to the original view,
GENDER HAVING
you can click on this.
COUNT(GENDER)>3")
result = cursor.fetchall()
2) Forward / Back buttons:
co = [i[0] for i in cursor.description] These buttons can be used like the
print(co) Forward and Back buttons in your browser.
print(result) You can click these to move back to the
43. Explain the characteristics of an algorithm. previous point you were at, or forward
Input Zero or more quantities to be again.
supplied. 3) Pan Axis:
Output At least one quantity is produced. This cross-looking button allows you to
click it, and then click and drag your graph
Finiteness Algorithms must terminate after around.
finite number of steps. 4) Zoom:
Definiteness All operations should be well The Zoom button lets you click on it, then
defined. For example operations click and drag a square that you would like
involving
to zoom into specifically. Zooming in will
division by zero or taking square
require a left click and drag. You can
root for negative number are
unacceptable.
alternatively zoom out with a right click and
Effectiveness Every instruction must be carried
drag.
out effectively.
5) Configure Subplots:
Correctness The algorithms should be error This button allows you to configure various
free. spacing options with your figure and plot.
Simplicity Easy to implement. 6) Save Figure:
Unambiguous Algorithm should be clear and This button will allow you to save your
unambiguous. Each of its steps figure in various forms.
and their
inputs/outputs should be clear and
must lead to only one meaning.
Feasibility Should be feasible with the
available resources.
Portable An algorithm should be generic,
independent of any programming
language or an operating system
able to handle all range of inputs.
Independent An algorithm should have step-by-
step directions, which should be
independent of any programming
code.
Page 23 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
45. Explain in detail the types of pyplots using 3) Pie Chart
Matplotlib. Pie Chart is probably one of the most
1) Line Chart common type of chart.
A Line Chart or Line Graph is a type of chart It is a circular graphic which is divided into
which displays information as a series of slices to illustrate numerical proportion.
data points called „markers‟ connected by The point of a pie chart is to show the
straight line segments. relationship of parts out of a whole.
A Line Chart is often used to visualize a To make a Pie Chart with Matplotlib, we
trend in data over intervals of time – a time can use the plt.pie() function.
series–thus the line is often drawn The autopct parameter allows us to display
chronologically. the percentage value using the Python
Example: Line plot string formatting.
import matplotlib.pyplot as plt Example:
years = [2014, 2015, 2016, 2017, 2018] import matplotlib.pyplot as plt
total_populations = [8939007, 8954518, sizes = [89, 80, 90, 100, 75]
8960387, 8956741, 8943721] labels = ["Tamil", "English", "Maths",
plt.plot (years, total_populations) "Science", "Social"]
plt.title ("Year vs Population in India") plt.pie (sizes, labels = labels, autopct =
plt.xlabel ("Year") "%.2f")
plt.ylabel ("Total Population") plt.show()
plt.show() Output:
Output:
2) Bar Chart
A BarPlot (or BarChart) is one of the most
common type of plot. 46. Identify in the following program
It shows the relationship between a let rec gcd a b :=
numerical data and a categorical values. if b <> 0 then gcd b (a mod b) else
Bar chart represents categorical data with return a
rectangular bars. i) Name of the function
ii) Identify the statement which tells it is a
Each bar has a height corresponds to the
recursive function
value it represents. iii) Name of the argument variable
The bars can be plotted vertically or iv) Statement which invoke the function
horizontally. recursively
It‟s useful when we want to compare a given v) Statement which terminates the
numeric value on different categories. recursion
To make a bar chart with Matplotlib, we can Ans:
use the plt.bar() function. i) gcd
Example: ii) let rec gcd a b :=
import matplotlib.pyplot as plt iii) a,b
labels = ["TAMIL", "ENGLISH", "MATHS", iv) if b<>0 then gcd b (a mod b)
"PHYSICS", "CHEMISTRY", "CS"] v) return a
usage = [79.8, 67.3, 77.8, 68.4, 70.2, 88.5] 47. Write a program to display all 3 digit odd
y_positions = range (len(labels)) numbers.
plt.bar (y_positions, usage) for x in range (101,1000,2):
plt.xticks (y_positions, labels) print(x,end=‟\t‟)
plt.ylabel ("RANGE") 48. Write a program to display multiplication
plt.title ("MARKS") table for a given number.
plt.show()
Output:
num=int(input(“Enter the number for table:”))
term=int(input(“Enter the no. of terms:”))
for i in range(1,term+1):
print(i,”x”,n,”=”,ixn)
Page 24 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
49. Write a Python code to find the L.C.M. of 53. Write a Python program to execute the
two numbers. following c++ coding
a=int(input(“Enter the First Number:”)) #include <iostream>
b=int(input(“Enter the Second Number:”)) using namespace std;
if(a>b): int main()
min=a { cout<<“WELCOME”;
else: return(0);
min=b }
while(1): The above C++ program is saved in a file
if (min%a==0and min%b==0): welcome.cpp
print(“L.C.M is:” min) Python Program:
break #Now select File→New in Notepad and type
min=min+1 the Python program
Output:
Enter the first number: 5 # Save the File as pali.py . Program that
Enter the second number: 2 compiles and executes a .cpp file
L.C.M is: 10 # Python c:\pyprg\pali.py -i c:\pyprg\pali_cpp
50. Construct the following SQL statements in
the student table- import sys, os, getopt
(i) SELECT statement using GROUP BY def main(argv):
clause. opts, args = getopt.getopt(argv, "i:")
(ii) SELECT statement using ORDER BY
clause. for o, a in opts:
(i) SELECT gender FROM student GROUP if o in "-i":
BY gender;
(ii) SELECT *FROM student ORDER BY run(a)
name; def run(a):
51. Write a SQL statement to create a table for
employee having any five fields and create inp_file=a+'.cpp'
a table constraint for the employee table. exe_file=a+'.exe'
CREATE TABLE employee
( os.system('g++'+inp_file+'-o'+ exe_file)
EmpcodeChar(25) NOT NULL, os.system(exe_file)
EmpnameChar(20), if __name__=='__main__':
Design Varchar(15),
Pay Integer, main(sys.argv[1:])
Allowance Integer, 54. Explain each word of the following
PRIMARY KEY(Empcode)Table Constraint command.
); Python <filename.py> -<i> <C++ filename
52. Write a Python program to write a CSV without cpp extension>
File with custom quotes.
import csv Python keyword to execute the
csvData = [[„SNO‟,‟Items‟],[„1‟,‟Pen‟],[„2‟,‟Book‟], Python program from
[„3‟,‟Pencil‟]] command-line
csv.register_dialect(„myDialect‟,delimiter=„|‟,quotechar
=„”‟,quoting=csv.QUOTE_ALL) filename.py Name of the Python program
with open(„c:\pyprg\ch13\quote.csv‟,„w‟,newline„=‟) as
csvFile: to executed
writer = csv.writer (csvFile, dialect=‟myDialect‟)
writer.writerows(csvData) -i input mode
print(“writing completed”)
csvFile.close() C++ filename name of C++ file to be
without cpp compiled and executed
extension
Page 25 of 26
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE MLM 5 Marks ISAAC EBINEZAR V
55. Consider the following table Supplier and item 57. Write a Python script to create a table called ITEM
.Write a python script for (i) to (ii) with following specification.
SUPPLIER Add one record to the table.
Suppno Name City Icode SuppQty Name of the database :- ABC
S001 Prasad Delhi 1008 100 Name of the table :- Item
S002 Anu Bangalore 1010 200 Column name and specification :-
S003 Shahid Bangalore 1008 175
Icode :- integer and act as
S004 Akila Hydrabad 1005 195 primary key
S005 Girish Hydrabad 1003 25 Item Name :- Character with length 25
S006 Shylaja Chennai 1008 180 Rate :- Integer
S007 Lavanya Mumbai 1005 325 Record to be added :- 1008, Monitor,15000
i) Display Name, City and Itemname of Python Script:
suppliers who do not reside in Delhi. import sqlite3
ii) Increment the SuppQty of Akila by 40 connection=sqlite3.connect(“ABC.db”)
ans: i) sql_command=”””CREATE TABLE Item(Icode
import sqlite3 INTEGER PRIMARY KEY,
connection=sqlite3.connect("ABC.db") ItemNAme VARCHAR(25), Rate
cursor = connection.cursor() INTEGER);”””
cursor.execute("SELECT Supplier.Name, cursor.execute(sql_command)
Supplier.City, sql_command=””” INSERT INTO Item
Item.ItemName FROM (Icode, ItemName, Rate)
Supplier,Item WHERE VALUES(1008,‟Monitor‟,15000);
Supplier.Icode=Item.Icode ”””
cursor.execute(sql_command)
AND Supplier.City NOT In connection.commit()
Delhi”) connection.close()
s= [i[0] for I in cursor.description] print(“TABLE CREATED”)
print(s) 58. Consider the following employee table. Write SQL
result=cursor.fetchall() commands for the qtns.(i) to (v).
for r in result: EMP
CODE
NAME DESIG PAY ALLOWANCE
print(r) S1001 Hariharan Superviosor 29000 12000
P1002 Shaji Operator 10000 5500
P1003 Prasad Operator 12000 6500
ans: ii) C1004 Manjima Clerk 8000 4500
import sqlite3 M1005 Ratheesh mechanic 20000 7000
connection=sqlite3.connect("ABC.db") (i) To display the details of all employees in
cursor = connection.cursor() descending order of pay.
cursor.execute("UPDATE Supplier ST (ii) To display all employees whose allowance is
between 5000 and 7000.
SuppQty = SuppQty +40 (iii) To remove the employees who are mechanic.
WHERE Name=‟Akila‟”) (iv) To add a new row.
cursor.commit() (v) To display the details of all employees who are
result = cursor.fetchall() operators.
print(*result,sep="\n") Answer:
(i) SELECT *FROM employee ORDER BY PAY
connection.close() DESC;
56. Write the Python script to display all the (ii) SELECT *FROM employee WHERE
records of the following table using ALLOWANCE BETWEEN 5000 AND 7000;
fetchmany() (iii) DELETE FROM employee WHERE
Icode ItemName Rate DESIGN=‟mechanic‟;
1003 Scanner 10500 (iv) INSERT INTO employee VALUES(S1006, Sam,
1004 Speaker 3000 „supervisor‟, 29000, 12000);
1005 Printer 8000 (v) SELECT *FROM employee WHERE DESIGN =
1008 Monitor 15000 „operator‟;
1010 Mouse 700 59. Explain the purpose of the following
Python Script: functions:
import sqlite3 a. plt.xlabel
connection=sqlite3.connect(“Materials.db”) b. plt.ylabel
cursor.execute(SELECT *FROM Materials”) c. plt.title
print(“Display All the Records”) d. plt.legend()
result=cursor.fetchmany(5) e. plt.show()
print(result,sep=”\n”) Answer:
a. plt.xlabel - specifies label for X-axis
b. plt.ylabel - specifies label for Y-axis
c. plt.title - specifies title to the graph
d. plt.legend( ) - you can invoke the default legend
e. plt.show( ) - function inside the file to display your
plot.
Page 26 of 26