0% found this document useful (0 votes)
26 views25 pages

Xii - CS - MLM

Uploaded by

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

Xii - CS - MLM

Uploaded by

ftgamer15092007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

12

HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE

XII - COMPUTER SCIENCE


CHAPTER – 1 – FUNCTION  Pure functions are functions which
PART – II will give exact result when the same
1. What is a subroutine? arguments are passed.
 Subroutines are small sections of code  The strlen is a pure function because
that are used to perform a particular the function takes one variable as a
task that can be used repeatedly. parameter, and accesses it to find its
2. Define Function with respect to length.
Programming language. 3. What is the side effect of impure
 A function is a unit of code that is oft function? Give example.
en defined within a greater code  A function has side effects when it has
structure. observable interaction with the outside
3. Write the inference you get from world.
X:=(78).  Example:
(X : int) let y: = 0
4. Differentiate interface and (int) inc (int) x
implementation. y: = y + x;
Interface Implementation return (y)
Interface just Implementation 4. Differentiate pure and impure
defines what an carries out the function.
object can do, but instructions Pure Function Impure Function
won’t actually do defined in the The return value The return value
it interface depends on its does not solely
arguments passed. depend on its
5. Which of the following is a normal arguments passed.
function definition and which is if you call the pure if you call the
recursive function definition? functions with the impure functions
i) let sum x y: same set of with the same set of
return x + y arguments, you arguments, you
ii) let disp : will always get the might get the
print ‘welcome’ same return different return
iii) let rec sum num: values. values
if (num!=0) then return num + sum They do not have They have side
(num-1) any side effects. effects
else PART - IV
return num 1. What are called Parameters and write
Answer: a note on
(i) Normal function (i) Parameter without Type (ii)
(ii) Normal function Parameter with Type
(iii) Recursive function Parameters are the variables in a function
PART - III definition and arguments are the values
1. Mention the characteristics of which are passed to a function definition.
Interface. (i) Parameter without Type
 The class template specifies the  Example:
interfaces to enable an object to be (requires: b>=0 )
created and operated properly. (returns: a to the power of b)
 An object's attributes and behavior is let rec pow a b:=
controlled by sending functions to if b=0 then 1
the object. else a * pow a (b-1)
2. Why strlen is called pure function?
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 1 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
 In the above function definition  The variables used inside the function
variable ‘b’ is the parameter and the may cause side effects though the
value which is passed to the variable functions which are not passed with any
‘b’ is the argument. arguments. In such cases the function is
(ii) Parameter with Type called impure function.
 Example:  Example:
(requires: b> 0 ) let Random number
(returns: a to the power of b ) let a := random()
let rec pow (a: int) (b: int) : int := if a > 10 then return: a
if b=0 then 1 else return: 10
else a * pow b (a-1)
 When we write the type annotations CHAPTER 2 - DATA ABSTRACTION
for ‘a’ and ‘b’ the parentheses are PART - II
mandatory. 1. What is abstract data type?
2. Identify in the following program  Abstract Data type (ADT) is a type (or
let rec gcd a b := class) for objects whose behavior is
if b <> 0 then gcd b (a mod b) else defined by a set of value and a set of
return a operations.
i) Name of the function 2. Differentiate constructors and
ii) Identify the statement which tells it is a selectors.
recursive function Constructor Selectors
iii) Name of the argument variable Constructors are Selectors are
iv) Statement which invoke the function functions that functions that
recursively build the abstract retrieve information
v) Statement which terminates the data type. from the data type.
recursion 3. What is a Pair? Give an example.
Answer:  Any way of bundling two values together
(i) Name of the function gcd into one can be considered as a pair.
 Example: lst[(0, 10), (1, 20)]
(ii) Identify the statement which gcd b (a
tells it is a recursive function mod b)
4. What is a List? Give an example.
(iii) Name of the argument
a, b  List is constructed by placing
variable expressions within square brackets
(iv) Statement which invoke the separated by commas.
(a mod b)
function recursively  Example: lst := [10, 20]
(v) Statement which terminates 5. What is a Tuple? Give an example.
return a
the recursion  A tuple is a comma-separated
3. Explain Pure and impure functions sequence of values surrounded with
with an example. parentheses.
Pure functions: PART - III
 Pure functions are functions which will 1. Differentiate Concrete data type and
give exact result when the same abstract data type.
arguments are passed. Concrete data type Abstract data type
 A function can be a pure function A concrete data type An abstract data type
provided it should not have any external is a data type whose the representation of
variable which will alter the behavior of representation is a data type is
that variable. known. unknown.
 Example: 3. Identify which of the following are
let square x constructors and selectors?
return: x * x Answer:
Impure functions: (a) N1=number() Constructor

RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 2 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
(b) accetnum(n1) Selector rational(n, d):
(c) displaynum(n1) Selector return [n, d]
(d) eval(a/b) Selector numer(x):
(e) x,y= makeslope Constructor return x[0]
(f) display() Selector denom(x):
5. Identify Which of the following are return x[1]
List, Tuple and class?
Answer: CHAPTER 3 - SCOPING
(a) arr [1, 2, 34] List PART - II
(b) arr (1, 2, 34) Tuple 1. What is a scope?
(c) student [rno, name, mark] Class  Scope refers to the visibility of variables,
parameters and functions in one part of
(d) day= (‘sun’, ‘mon’, ‘tue’, Tuple
a program to another part of the same
‘wed’)
program.
(e) x= [2, 5, 6.5, [5, 6], 8.2] List
3. What is mapping?
(f) employee [eno, ename, esal, Class
 The process of binding a variable name
eaddress]
with an object is called mapping.
PART - IV
4. What do you mean by Namespaces?
1. How will you facilitate data
 Namespaces are containers for mapping
abstraction? Explain it with suitable
names of variables to objects.
example
PART - III
 To facilitate data abstraction, you will
1. Define Local scope with an example.
need to create two types of functions:
 Local scope refers to variables defined in
Constructors and Selectors.
current function.
(i) Constructors:
 Example:
 Constructors are functions that build
1. Disp():
the abstract data type.
2. a:=7
 Example:
3. print a
distance(city1, city2):
4. Disp()
(ii) Selectors:
2. Define Global scope with an example.
 Selectors are functions that retrieve
 A variable which is declared outside of
information from the data type.
all the functions in a program is known
 Example:
as global variable.
-- constructor
 Example
makepoint(x, y):
1. a:=10
return x, y
2. Disp():
-- selector
3. a:=7
xcoord(point):
4. print a
return point[0]
5. Disp()
2. What is a List? Why List can be called
6. print a
as Pairs? Explain with suitable example
3. Define Enclosed scope with an
List:
example.
 List is constructed by placing
 A variable which is declared inside a
expressions within square brackets
function which contains another
separated by commas.
function definition with in it, the inner
 List can store multiple values. Each
function can also access the variable of
value can be of any type and can even be
the outer function.
another list.
 Example
Pairs:
1. Disp():
 Any way of bundling two values together
2. a:=10
into one can be considered as a pair.
3. Disp1():
Example:
4. print a
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 3 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
5. Disp1() 4. Module segments can be used by
6. print a invoking a name and some parameters.
7. Disp() 5. Module segments can be used by other
PART - IV modules.
1. Explain the types of scopes for variable CHAPTER 4 – ALGOR. STRATEGIES
or LEGB rule with example. Part - II
(i) Local scope: 1. What is an Algorithm?
 Local scope refers to variables defined in  An algorithm is a finite set of
current function. instructions to accomplish a particular
 Example: task.
1. Disp():  It is a step-by-step procedure for solving
2. a:=7 a given problem.
3. print a 2. Define Pseudo code.
4. Disp() It’s simply an implementation of an
(ii) Global scope: algorithm in the form of annotations and
 A variable which is declared outside informative text written in plain English.
of all the functions in a program is known 3. What is Insertion Sort?
as global variable. Insertion sort is a simple sorting algorithm. It
 Example works by taking elements from the list one by
1. a:=10 one and inserting then in their correct
2. Disp():
position in to a new sorted list.
3. a:=7
4. What is Sorting?
4. print a
Arranging elements (values) in a sequential
5. Disp()
order.
6. print a
(iii) Enclosed scope:
5. What is searching? Write its types.
 A variable which is declared inside a
 Finding a particular element (value)
function which contains another function
from a set is called as searching.
definition with in it, the inner function can
 Types of searching:
also access the variable of the outer
o Linear Search
function.
o Binary Search
 Example
PART - III
1. Disp():
1. List the characteristics of an
2. a:=10
algorithm.
3. Disp1():
4. print a  Input  Simplicity
5. Disp1()  Output  Unambiguous
6. print a  Finiteness  Feasibility
7. Disp()  Definiteness  Portable
(iv) built-in scope:  Effectiveness  Independent
 Any variable or module which is  Correctness
defined in the library functions of a 2. Discuss about Algorithmic complexity
programming language has Built-in or and its types.
module scope.  The complexity of an algorithm f (n) gives
2. Write any Five Characteristics of the running time and/or the storage
Modules. space required by the algorithm in terms
1. Modules contain instructions, of n as the size of input data.
processing logic, and data.  Time Complexity: The Time complexity
2. Modules can be separately compiled and of an algorithm is given by the number
stored in a library. of steps taken by the algorithm to
3. Modules can be included in a program. complete the process.

RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 4 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
 Space Complexity: Space complexity of  Binary search also called half-interval
an algorithm is the amount of memory search algorithm. It finds the position of
required to run to its completion. a search element within a sorted array.
PART - IV  Pseudo code:
1. Explain the characteristics of an 1. Start with the middle element:
algorithm.  If the search element is equal to the
Input Zero or more quantities to be middle element of the array return
supplied. the index of the middle element.
Output At least one quantity is  If not, then compare the middle
produced. element with the search value
Finiteness Algorithms must terminate after  If the search element is greater than
finite number of steps. the number in the middle index, then
Definitene All operations should be well select the elements to the right side
ss defined. of the middle index, and go to Step-
Effectiven Every instruction must be 1.
ess carried out effectively.  If the search element is less than the
Correctne The algorithms should be error number in the middle index, then
ss free. select the elements to the left side of
Simplicity Easy to implement. the middle index, and start with
Unambigu Algorithm should be clear and Step-1.
ous unambiguous. 2. When a match is found, display the
Feasibility Should be feasible with the index of the element matched.
available resources. 3. If no match is found for all comparisons,
Portable An algorithm should be generic, then display unsuccessful message.
independent 4. Explain the Bubble sort algorithm with
example.
Independe An algorithm should have step-
nt by-step directions, which should  Bubble sort is a simple sorting
be independent of any algorithm.
programming code.  The algorithm starts at the beginning of
2. Discuss about Linear search algorithm. the list of values stored in an array.
 Linear search also called sequential  It compares each pair of adjacent
search. elements and swaps them if they are in
the unsorted order.
 This method checks the search element
with each element in sequence until the  This comparison and passed to be
desired element is found or the list is continued until no swaps are needed.
exhausted.  Pseudo code
 Pseudo code: 1. Start with the first element i.e., index
1. Traverse the array = 0, compare the current element with
2. In every iteration, compare the the next element of the array.
search key value with the current value of 2. If the current element is greater than
the list. the next element of the array, swap
them.
 If the values match, display the current
3. If the current element is less than the
index and value of the array
next or right side of the element, move to
 If the values do not match, move on to
the next element. Go to Step 1 and
the next array element.
repeat until end of the index is reached.
3. If no match is found, display the
search element not found.
Chapter - 5
3. What is Binary search? Discuss with
PYTHON - VARIABLES AND OPERATORS
example.
PART - II

RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 5 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
1. What are the different modes that can Operator -
Examples Result
be used to test Python Program? Operation
 Interactive Mode Assume a=100 and b=10.
 Script Mode + (Addition) >>> a + b 110
2. Write short notes on Tokens. - (Subtraction) >>>a – b 90
 Python breaks each logical line into a *
sequence of elementary lexical >>> a*b 1000
(Multiplication)
components known as Tokens. / (Division) >>> a / b 10.0
 The normal token types are % (Modulus) >>> a % 30 10
Identifiers, Keywords, Operators, ** (Exponent) >>> a ** 2 10000
Delimiters and Literals. // Floor >>> a//30
3. What are the different operators that 3
Division (Integer Division)
can be used in Python? 2. What are the assignment operators
1) Arithmetic operators that can be used in Python?
2) Relational or Comparative operators Op Example
3) Logical operators era Description (Assume:
4) Assignment operators tor x=10)
5) Conditional operator
Assigns right side >>> x=10
4. What is a literal? Explain the types of =
operands to left variable >>> b=”CS”
literals?
Added and assign back >>> x+=20
 Literal is a raw data given in a +=
the result to left operand # x=x+20
variable or constant.
Subtracted and assign
Types of Literals: >>> x-=5
-= back the result to left
Numeric Literals # x=x-5
operand
 Numeric Literals consists of digits
Multiplied and assign
and are immutable >>> x*=5
*= back the result to left
 Numeric literals can belong to 3 operand
# x=x*5
different numerical types Integer,
Divided and assign back >>> x/=2
Float and Complex. /=
the result to left operand # x=x/2
String Literals
Taken modulus using
 In Python a string literal is a %= two operands and assign
>>> x%=3
sequence of characters surrounded # x=x%3
the result to left operand
by quotes.
Performed exponential
Boolean Literals
(power) calculation on >>> x**=2
 A Boolean literal can have any of the **=
operators and assign # x=x**2
two values: True or False. value to the left operand
Escape Sequences
Performed floor division
 In Python strings, the backslash "\" //= on operators and assign >>> x//=3
is a special character, also called the value to the left operand
"escape" character. 3. Explain Ternary operator with
5. Write short notes on Exponent data? examples.
An Exponent data contains decimal digit Ternary operator is also known as
part, decimal point, exponent part followed conditional operator that evaluates
by one or more digits. Eg.: 12.E04, 24.e04 something based on a condition being true
PART - III or false.
1. Write short notes on Arithmetic The Syntax:
operator with examples. Variable Name = [on_true] if [Test
An arithmetic operator is a mathematical expression] else [on_false]
operator that takes two operands and Example:
performs a calculation on them. min= 50 if 49 < 50 else 70
min= 50 if 49 > 50 else 70
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 6 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
4. Write short notes on Escape sequences In Python, the print() function is used to
with examples. display result on the screen.
 The backslash "\" is a special character,  The syntax:
also called the "escape" character. print(“string to be displayed as output ” )
 It is used in representing certain print(variable )
whitespace characters: "\t" is a tab, "\n"  The print( ) displays an entire statement
is a newline, and "\r" is a carriage return. which is specified within print( ).
E.S.  Comma ( , ) is used as a separator in
Example Output
char. print ( ) to print more than one item.
\\ print("\\test") \test  Example:
\’ print("Doesn\'t") Doesn't >>> print (“Welcome to Python Program.”)
\” print("\"Python\"") "Python" Welcome to Python Program.
>>> x = 5
\n print("Py","\n","Lang..") Py Lang..
>>> print (x)
\t print("Py","\t","Lang..") Py Lang.. 5
5. What are string literals? Explain. 3. Discuss in detail about Tokens in
 In Python a string literal is a sequence of Python
characters surrounded by quotes. Python breaks each logical line into a
 Python supports single, double and triple sequence of elementary lexical components
quotes for a string. known as Tokens. 1) Identifiers, 2)
Example Program: Keywords, 3) Operators, 4) Delimiters and
strings = "This is Python" 5) Literals.
char = "C" (1) Identifiers
print (strings)  An Identifier is a name used to identify a
print (char) variable, function, class, module or
PART - IV object.
2. Explain input() and print() functions  An identifier must start with an alphabet
with examples. (A..Z or a..z) or underscore ( _ ).
 A program needs to interact with the  Identifiers may contain digits (0 .. 9)
user to accomplish the desired task; this  Python identifiers are case sensitive i.e.
can be achieved using Input-Output uppercase and lowercase letters are
functions. distinct.
 The input() function helps to enter data  Identifiers must not be a python
at run time by the user keyword.
 The output function print() is used to  Python does not allow punctuation
display the result of the program on the character such as %,$, @ etc., within
screen after execution. identifiers.
The input( ) function  Eg.: Sum, total_marks, regno, num1
The syntax: (2) Keywords
Variable = input (“prompt string”)
 Keywords are special words used by
 If a prompt string is used, it is displayed Python interpreter to recognize the
on the monitor; the user can provide structure of program.
expected data from the input device.
 Example: and, del, global etc.,
 The input( ) takes whatever is typed from (3) Operators
the keyboard and stores the entered data Operators are special symbols which
in the given variable. represent computations, conditional
 The input ( ) accepts all data as string or matching etc.
characters but not as numbers. (i) Arithmetic operators - performs a
Example: calculation on two operands.
>>> city=input (“Enter Your City: ”)  Operators: +, -, *, /, %, **, //
Enter Your City: Madurai
The print() function
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 7 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
(ii) Relational or Comparative operators -  Sequential
checks the relationship between two  Alternative or Branching
operands. If the relation is true, it returns  Iterative or Looping
True; otherwise it returns False. 2. Write note on break statement.
 Operators: ==, >, >=, <, <=, !=  The break is a jump statement.
(iii) Logical operators - perform logical  The breakstatement terminates the
operations on the relational expressions. loop containing it.
 Operators: and, or, not. 3. Write the syntax of if..else statement
(iv) Assignment operators if <condition>:
 Assignment operator to assign values statements-block 1
to variable. else:
 Operators statements-block 2
+=, -=, *=, /=, %=, **=, //= 4. Define control structure.
(v) Conditional operator - evaluates based A program statement that causes a jump of
on a condition being true or false. control from one part of the program to
 The Syntax: Variable Name = another is called control structure or
[on_true] if [Test expression] else [on_false] control statement.
(4) Delimiters - uses the symbols and 5. Write note on range() in loop
symbol combinations as delimiters in  The range() generates a list of values
expressions, lists, dictionaries and strings. starting from start till stop-1.
o Examples: ( ), { }, [ ]  The syntax of range():
(5) Literals range (start, stop, [step])
 Literal is a raw data given in a variable start – refers to the initial value
or constant. stop – refers to the final value
 Types of Literals: 1) Numeric 2) String 3) step – refers to increment value
Boolean 4) Escape sequences PART-III
(i) Numeric Literals 1. Write a program to display
 Numeric Literals consists of digits and A
are immutable AB
 Numeric literals can belong to 3 different ABC
numerical types Integer, Float and ABCD
Complex. ABCDE
(ii) String Literals for i in range (65, 70):
 String literal is a sequence of characters for j in range (65, i+1):
surrounded by quotes. print(chr(j), end=' ')
 Python supports single, double and print("")
triple quotes for a string. 2. Write note on if..else structure.
(iii) Boolean Literals  The if .. else statement provides control
 A Boolean literal can have any of the two to check the true block as well as the
values: True or False. false block.
(iv) Escape Sequences  Syntax:
 In Python strings, the backslash "\" is a if <condition>:
special character, also called the statements-block 1
"escape" character. else:
 It is used in representing certain statements-block 2
whitespace characters: "\t" is a tab, "\n" 3. Using if..else..elif statement write a
is a newline, and "\r" is a carriage suitable program to display largest of 3
return. numbers.
Chapter – 6 - CONTROL STRUCTURES num1=int(input("Enter number 1: "))
PART -II num2=int(input("Enter number 2: "))
1. List the control structures in Python. num3=int(input("Enter number 3: "))
if (num1 > num2):
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 8 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
large=num1 statements-block 1
elif (num2 > num3): elif<condition-2>:
large=num2 statements-block 2
else: else:
large=num3 statements-block n
print("The Largest number is: ",large) In the syntax of if..elif..else mentioned
4. Write the syntax of while loop. above, condition-1 is tested if it is true
while <condition>: thenstatements-block1 is executed,
statements block 1 otherwise the control checks condition-2, if
[else: it is true statementsblock2is executed and
statements block2] even if it fails statements-block n mentioned
5. List the differences between break and in else part is executed.
continue statements. Example:
Break Continue m1=int (input(“Enter 1st subject mark: ”))
Itis used terminates It is used to skip m2=int (input(“Enter 2nd subject mark: ”))
the loop containing the remaining part avg= (m1+m2)/2
it. of a loop and start if avg>=80:
Control of the with next iteration print (“Grade : A”)
program flows to the elif avg>=70 and avg<80:
statement print (“Grade : B”)
immediately after the elif avg>=60 and avg<70:
body of the loop print (“Grade : C”)
PART -IV elif avg>=50 and avg<60:
1. Write a detail note on for loop print (“Grade : D”)
 The forloop is the most comfortable loop. else:
 It is also an entry check loop. print (“Grade : E”)
 The condition is checked in the 3. Write a program to display all 3 digit
beginning and the body of the loopis odd numbers.
executed if it is only True otherwise the Program:
loop is not executed. for i in range(101,1000,2):
 Syntax: print (i,end='\t')
for counter_variable in sequence: 4. Write a program to display
statements-block 1 multiplication table for a given number.
[else: # optional block Program:
statements-block 2] num=int(input("Enter a number: "))
for i in range(1,16):
 forloop uses the range() function. print(num," X ", i, " = ", num*i)
 The range() generates a list of values Chapter – 7 - PYTHON FUNCTIONS
PART - II
starting from starttill stop-1.
1. What is function?
 The syntax of range():
 Functions are named blocks of code
range (start,stop,[step])
that are designed to do specific job.
1. start – refers to the initial value
2. Write the different types of function.
2. stop – refers to the final value
1. User defined functions
3. step – refers to increment value
2. Built in functions
 Example:
3. Recursive functions
for i in range(2,10,2):
4. Lambda functions
print (i,end=' ')
3. What are the main advantages of
2. Write a detail note on if..else..elif
function?
statement with suitable example.
 It avoids repetition and makes high
Syntax:
degree of code reusing.
if <condition-1>:

RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 9 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
 It provides better modularity for your print(year, " is a Leap year")
application. else:
4. What is meant by scope of variable? print(year, " is not a Leap year")
Mention its types. y=int(input("Enter a year : "))
 Scope of variable refers to the part of leap(y)
the program, where it is accessible, PART - IV
i.e., area where you can refer (use) it. 1. Explain the different types of function
 Types of scopes: with an example.
o Local scope and Global scope. In Python, the functions are classified as
5. Define global scope. different types.
A variable, with global scope can be used I. User defined functions
anywhere in the program. It can be created II. Built-in functions
by defining a variable outside the scope of III. Lambda functions
any function/block. IV. Recursive functions
PART - III (I) User defined functions:
1. Write the rules of local variable. When defining functions there are multiple
1. A variable with local scope can be things that need to be noted:
accessed only within the function/block  Function blocks begin with the keyword
that it is created in. “def” followed by function name and
2. When a variable is created inside the parenthesis ().
function/block, the variable becomes  Any input parameters or arguments
local to it. should be placed within these
3. A local variable only exists while the parentheses when define a function.
function is executing.  The code block always comes after a
2. Write the basic rules for global colon (:) and is indented.
keyword in python.  The statement “return [expression]”
1. When we define a variable outside a exits a function.
function, it’s global by default. You don’t  A “return” with no arguments is the
have to use global keyword. same as return None.
2. We use global keyword to read and write syntax of creating a user defined
a global variable inside a function. function:
3. Use of global keyword outside a function def <function_name( [para1, para2…)>:
has no effect <block of statements>
4. Differentiate ceil( ) and floor( ) return <expression/None>
function? Example:
ceil( ) floor( ) def leap(year):
Returns the Returns the largest if((year%4==0 and year%100!=0) or
smallest integer integer less than or (year%400==0)):
greater than or equal to the given print(year, " is a Leap year")
equal to the given value. else:
number print(year, " is not a Leap year")
General format: General format: y=int(input("Enter a year : "))
math.ceil(x) math.floor(x) leap(y)
Example: Example: (II) Built-in Functions:
import math import math The functions which are available with
x=26.7 x=26.7 Python by default is known as built-in
print(math.ceil(x)) print(math.floor(x)) functions.
5. Write a Python code to check whether (III) Lambda functions
a given year is leap year or not.  In Python, anonymous function is a
def leap(year): function that is defined without a name.
if((year%4==0 and year%100!=0) or  While normal functions are defined
(year%400==0)): using the def keyword, in Python
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 10 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
anonymous functions are defined using print(y)
the lambda keyword. loc()
 Hence, anonymous functions are also (II) Global Scope:
called as lambda functions.  Defining a variable outside the scope of
Syntax of lambda function: any function/block.
lambda [argument(s)]: expression  Global scope can be used anywhere in
Example: the program.
sqr=lambda x:x**2 Basic rules for global keyword in python:
num=int(input("Enter a number: "))  When we define a variable outside a
print("The sequre of ",num, " is ", function, it’s global by default. You don’t
sqr(num)) have to use global keyword.
(IV) Recursive functions  We use global keyword to read and write
 When a function calls itself is known as a global variable inside a function.
recursion. Example:
 The condition that is applied in any c=1
recursive function is known as base def add():
condition. print(c)
 A base condition is must in every add()
recursive function otherwise it will 3. Explain the following built-in
continue to execute like an infinite loop. functions. (a) id() (b) chr()
Example: (c) round() (d) type() (e) pow()
def fact(n): (a) id( )
if n == 0:  Returns the “identity of an object” ie.
return 1 the memory address of the object.
else:  Example:
return n * fact (n-1) X=15
print (fact (0)) print("Address of X is: ",id(X))
print (fact (5)) (b) chr( )
2. Explain the scope of variables with an  Returns the Unicode character for
example. the given ASCII value.
 Scope of variable refers to the part of the  Example:
program, where it is accessible, i.e., area Ch=65
where you can refer (use) it. print(“Unicode character of ”,
 Types of scopes: Ch, “is: ”, chr(Ch))
o Local scope and Global scope. (c) round( )
(I) Local Scope:  Returns the nearest integer to its
 A variable declared inside the function's input.
body or in the local scope is known as  General format:
local variable. round(number [,ndigits])
Rules of local variable:  Example:
 A variable with local scope can be accessed x=17.9
only within the function/block that it is rint('x value is rounded to', round(x))
created in. print('x value is rounded to',
 When a variable is created inside the round(y,2))
function/block, the variable becomes local (d) type( )
to it.  Returns the type of an object for the
 A local variable only exists while the given single object.
function is executing.  Example: X= 15
Example: print(type(X))
def loc(): (e) pow( )
y=0

RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 11 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
 Returns the computation of a raised 1. Write a Python program to display the
to the power of b. given pattern
 Example: x=5 COMPUTER
y=2 COMPUTE
print(pow(x,y)) COMPUT
5. Explain recursive function with an COMPU
example. COMP
 When a function calls itself is known as COM
recursion. CO
 The condition that is applied in any C
recursive function is known as base Coding:
condition. str1="COMPUTER"
 A base condition is must in every index=len(str1)
recursive function otherwise it will for i in str1:
continue to execute like an infinite loop. print(str1[0:index])
Working of recursive function: index-=1
 Recursive function is called by some 2. Write a short about the followings with
external code. suitable example:
 If the base condition is met then the (a) capitalize( ) (b) swapcase( )
program gives meaningful output and (a) capitalize( )
exits.  Used to capitalize the first character
 Otherwise, function does some required of the string.
processing and then calls itself to Example:
continue recursion. >>> city="chennai"
Example: >>> print(city.capitalize())
def fact(n): Chennai
if n == 0: (b) swapcase( )
return 1  This function will change case of
else: every character to its opposite case
return n * fact (n-1) vice-versa.
print (fact (0)) Example:
print (fact (5)) >>> str1="tAmiL NaDu"
>>> print(str1.swapcase())
Chapter – 8 TaMIl nAdU
STRINGS AND STRING MANIPULATION 3. What will be the output of the given
PART -II python program?
1. What is String? str1 = "welcome"
 String is a sequence of Unicode str2 = "to school"
characters that may be a combination of str3=str1[:2]+str2[len(str2)-2:]
letters, numbers, or special symbols print(str3)
enclosed within single, double or even Output:
triple quotes. weol
4. What will be the output of the PART -IV
following python code? 1. Explain about string operators in
str1 = “School” python with suitable example.
print(str1*3) String Operators:
Output:  Python provides the following operators
SchoolSchoolSchool for string operations. These operators
5. What is slicing? are useful to manipulate string.
 Slice is a substring of a main string. (i) Concatenation (+)
PART -III  Joining of two or more strings is called
as Concatenation.
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 12 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
 The plus (+) operator is used to  A negative index can be used to access an
concatenate strings in python. element in reverse order.
Example 3. What will be the value of x in following
>>> "welcome" + "Python" python code?
'welcomePython' List1=[2,4,6[1,3,5]]
(ii) Append (+ =) x=len(List1)
 Adding more strings at the end of an Answer: 4
existing string is known as append. 4. Differentiate del with remove( ) function of
 The operator += is used to append a List.
new string with an existing string.  The del statement is used to delete known
Example elements whereas
>>> str1="Welcome to "  The remove( ) function is used to delete
>>> str1+="Learn Python" elements of a list if its index is unknown.
>>> print (str1) 6. What is set in Python?
Welcome to Learn Python  A Set is a mutable and an unordered
(iii) Repeating (*) collection of elements without duplicates.
 The multiplication operator (*) is PART - III
used to display a string in multiple 1. What are the advantages of Tuples over a
number of times. list?
Example 1. The elements of a list are changeable
>>> str1="Welcome " (mutable) whereas the elements of a tuple
>>> print (str1*4) are unchangeable (immutable), this is the
key difference between tuples and list.
Welcome Welcome Welcome Welcome
2. The elements of a list are enclosed within
(iv) String slicing
square brackets. But, the elements of a tuple
 Slice is a substring of a main string.
are enclosed by paranthesis.
 A substring can be taken from the 3. Iterating tuples is faster than list.
original string by using [ ] operator 2. Write a shot note about sort( ).
and index or subscript values. Thus,  The sort( ) is used to sorts the elements
[ ] is also known as slicing operator. in a list.
 Using slice operator, you have to slice  The general format:
one or more substrings from a main List.sort(reverse=True|False, key=myFunc)
string.  Both, reverse and key arguments are
 General format of slice operation: optional
str[start:end] o If reverse is set to True, the list
Example I: slice a single character from a will be sorted in descending order
string o Ascending is default.
>>> str1="THIRUKKURAL"  Example:
>>> print (str1[0]) MyList=['B','G','Z','A','V']
T MyList.sort()
>>> print (str1[0:5]) print(MyList)
THIRU 3. What will be the output of the following
code?
Chapter – 9 list = [2**x for x in range(5)]
LISTS, TUPLES, SETS AND DICTIONARY print(list)
PART - II Output:
1. What is List in Python? [1, 2, 4, 8, 16]
 A list in Python is known as a “sequence data 4. Explain the difference between del and
type” like strings. clear( ) in dictionary with an example.
 It is an ordered collection of values enclosed  In Python dictionary, del keyword is used
within square brackets [ ]. to delete a particular element.
2. How will you access the list elements in  The clear( ) function is used to delete all
reverse order? the elements in a dictionary.
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 13 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
 To remove the dictionary, you can use (ii) Intersection:
del keyword with dictionary name.  It includes the common elements in two sets
 Example:  The operator & is used to intersect two sets
Dict = {'Roll' : 12001, 'SName' : 'Meena', in python.
'Mark1' : 98, 'Marl2' : 86}  The function intersection( ) is also used to
del Dict['Mark1'] intersect two sets in python.
Dict.clear() Example :
del Dict setA={'A', 2, 4, 'D'}
5. List out the set operations supported by setB={'A', 'B', 'C', 'D'}
python. print(setA & setB)
1. Union: It includes all elements from two or print(setA.intersection(set_B))
more sets (iii) Difference:
2. Intersection: It includes the common
 It includes all elements that are in first set but
elements in two sets not in the second set
3. Difference: It includes all elements that are
 The minus (-) operator is used to difference
in fi rst set (say set A) but not in the second
set operation in python.
set (say set B)
 The function difference( ) is also used to
4. Symmetric difference: It includes all the
difference operation.
elements that are in two sets but not the one
Example :
that are common to two sets.
PART - IV setA={'A', 2, 4, 'D'}
setB={'A', 'B', 'C', 'D'}
2. What is the purpose of range( )? Explain
print(setA - setB)
with an example.
print(setA.difference(setB))
 The range( ) is a function used to generate a
(iv) Symmetric difference:
series of values in Python.
 It includes all the elements that are in two
 Using range( ) function, you can create list
sets but not the one that are common to two
with series of values.
sets.
 Syntax of range ( ) function:
 The caret (^) operator is used to symmetric
range (start value, end value, step
difference set operation in python.
value)
 The function symmetric_difference( ) is
 The range( ) function has three arguments.
also used to do the same operation.
1. start value – beginning value of series. .
Example :
2. end value – upper limit of series.
setA={'A', 2, 4, 'D'}
3. step value – to generate different
setB={'A', 'B', 'C', 'D'}
interval of values.
print(setA ^ setB)
 Example: print(setA.symmetric_
for x in range (2, 11, 2): difference(setB))
print(x)
4. Explain the different set operations Chapter – 10
supported by python with suitable example. CLASSES AND OBJECTS
(i) Union: PART - II
 It includes all elements from two or more sets 1. What is class?
 In python, the operator | is used to union of  Class is the main building block in
two sets. Python.
 The function union( ) is also used to join two  Object is a collection of data and
sets in python. function that act on those data.
Example :  Class is a template for the object.
setA={2,4,6,8} 2. What is instantiation?
setB={'A', 'B', 'C', 'D'}  The process of creating object is
Uset=setA|setB called as “Class Instantiation”.
setU=setA.union(setB) 3. What is the output of the following
print(Uset) program?
print(setU)
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 14 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
class Sample: class Fruits:
__num=10 def __init__(self, f1, f2):
def disp(self): self.f1=f1
print(self.__num) self.f2=f2
S=Sample() def display(self):
S.disp() print("Fruit 1 = %s, Fruit 2 =
print(S.__num) %s" %(self.f1, self.f2))
Output: F = Fruits ('Apple', 'Mango')
10 del F.display
AttributeError: 'Sample' object has F.display()
no attribute '__num' Output:
4. How will you create constructor in Fruit 1 = Apple, Fruit 2 = Mango
Python? Error:
 In Python, there is a special function del F.display
called “init” which act as a Constructor. This statement deletes the object F,
It must begin and end with double Hence the Python shows attribute
underscore. error.
 This constructor function can be defined Correct Statement:
with or without arguments. F.display
 General format of __init__ method 4. What is the output of the following
def __init__(self, [args ……..]): program?
<statements> class Greeting:
5. What is the purpose of Destructor? def __init__(self, name):
 Destructor destroyed the objects were self.__name = name
created during instantiation.
 Used to clean up any resources used by it. def display(self):
PART -III print("Good Morning ",
1. What are class members? How do you self.__name)
define it?
 Variables defined inside a class are obj=Greeting('Bindu Madhavan')
called as “Class Variable” and obj.display()
functions are called as “Methods”. Output:
 Class variable and methods are together Good Morning Bindu Madhavan
known as members of the class. 5. How do define constructor and
 The class members should be accessed destructor in Python?
through objects or instance of class.  In Python, the constructors should
2. Write a class with two private class be defined using __init__ special
variables and print the sum using a function.
method.  Destructors defined using __del__
class Add: special function.
def __init__(self, num1, num2):
print("Constructor...") CHAPTER 11 - DATABASE CONCEPTS
self.__num1=num1 PART - II
self.__num2=num2 1. Mention few examples of a database.
Foxpro, Dbase, MS-Access,
def sum(self): OpenOfficeBase
s=self.__num1 + self.__num2 2. List some examples of RDBMS.
print("The sum=",s) SQL server, Oracle, mysql, MariaDB,
Res=Add(32,65) SQLite.
Res.sum() 3. What is data consistency?
3. Find the error in the following program
to get the given output?
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 15 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
 Data Consistency means that data This user group is involved in developing
values are the same at all instances of a and designing the parts of DBMS.
database  End User:
4. What is the difference between End users are the one who store,
Hierarchical and Network data model? retrieve, update and delete data.
Hierarchical data Network data  Database designers:
model model Database designers are responsible for
In hierarchical model, a In a Network model, identifying the data to be stored in the
child record has only one a child may have database for choosing appropriate
parent node many parent nodes. structures to represent and store the
5. What is normalization? data.
 Normalization reduces data redundancy PART - IV
and improves data integrity 1. Explain the different types of data
PART - III model.
1. What is the difference between Select Following are the different types of a Data
and Project command? Model
Select Project 1. Hierarchical Model
Symbol: σ Symbol: π 2. Relational Model
The projection 3. Network Database Model
The SELECT operation is 4. Entity Relationship Model
eliminates all
used for selecting a 5. Object Model
attributes of the
subset with tuples
input relation but 1. Hierarchical Model
according to a given
those mentioned in  Hierarchical model was developed by
condition. IBM as Information Management
the projection list.
2. What is the role of DBA? System.
 Database Administrator or DBA is the  In Hierarchical model, data is
one who manages the complete database represented as a simple tree like
management system. structure form.
 DBA takes care of the security of the  This model represents a one-to-many
DBMS, managing the license keys, relationship ie parent-child relationship.
managing user accounts and access etc. 2. Relational Model
3. Explain Cartesian Product with a  The Relational Database model was first
suitable example. proposed by E.F. Codd in 1970.
 Cross product is a way of combining two  The basic structure of data in relational
relations. The resulting relation model is tables (relations).
contains, both relations being  All the information’s related to a
combined. particular type is stored in rows of that
 A x B means A times B, where the table.
relation A and B have different  Hence tables are also known as relations
attributes. in a relational model.
 This type of operation is helpful to merge 3. Network Model
columns from two relations.  Network database model is an extended
5. Write a note on different types of form of hierarchical data model.
DBMS users.  The difference between hierarchical and
 Database Administrators: Network data model is:
Database Administrator or DBA is the o In hierarchical model, a child
one who manages the complete database record has only one parent node,
management system. o In a Network model, a child may
 Application Programmers or Software have many parent nodes.
Developers: 4. Entity Relationship Model. (ER model)

RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 16 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
 In this database model, relationship are associated with multiple records in
created by dividing the object into entity another table.
and its characteristics into attributes.
 It was developed by Chen in 1976. 3. Differentiate DBMS and RDBMS.
 It is very simple and easy to design Basics of
DBMS RDBMS
logical view of data. difference
5. Object Model Database Relational
 Object model stores the data in the form Expansion
Managem DataBase
of objects, attributes and methods, ent Management
classes and Inheritance. System System
 This model handles more complex Navigatio
Relational model (in
applications. nal model
Data tables). ie data in
 It is used in file Management System. It ie data by
storage tables as row and
represents real world objects, attributes linked
column
and behaviors. It provides a clear records
modular structure. Data
 It is easy to maintain and modify the redundanc Exhibit Not Present
existing code. y
2. Explain the different types of Not RDBMS uses
Normalizat
relationship mapping. performe normalization to
ion
1. One-to-One Relationship d reduce redundancy
2. One-to-Many Relationship Consume
Data Faster, compared to
3. Many-to-One Relationship s more
access DBMS.
4. Many-to-Many Relationship time
1. One-to-One Relationship: used to establish
 In One-to-One Relationship, one entity Keys and Does not relationship. Keys
is related with only one other entity. indexes use. are used in
 One row in a table is linked with only one RDBMS.
row in another table and vice versa. Inefficien
 For example: A student can have only Transactio t,
one exam number n Error Efficient and
2. One-to-Many Relationship: manageme prone secure.
 In One-to-Many relationship, one entity nt and
is related to many other entities. insecure.
 One row in a table A is linked to many Not
Distributed Supported by
rows in a table B, but one row in a table supporte
Databases RDBMS.
B is linked to only one row in table A. d
 For example: One Department has many SQL server, Oracle,
Dbase,
staff members. Example mysql, MariaDB,
FoxPro.
3. Many-to-One Relationship: SQLite.
 In Many-to-One Relationship, many 4. Explain the different operators in
entities can be related with only one in Relational algebra with suitable
the other entity. examples.
 For example: A number of staff members  Relational Algebra is divided into various
working in one Department. groups
 Multiple rows in staff members table is  Unary Relational Operations
related with only one row in Department 1. SELECT ( symbol : σ)
table. 2. PROJECT ( symbol : Π)
4. Many-to-Many Relationship  Relational Algebra Operations from Set
 A many-to-many relationship occurs Theory
when multiple records in a table are 3. UNION (∪)

RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 17 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
4. INTERSECTION (∩) 6. Security - The DBMS also takes care of
5. DIFFERENCE (−) the security of data, protecting the data
6. CARTESIAN PRODUCT (X) from unauthorized access.
(1) SELECT (symbol : σ) 7. DBMS Supports Transactions - It allows
 General form σc ( R ) with a relation R us to better handle and manage data
and a condition C on the attributes of R. integrity in real world applications where
 The SELECT operation is used for multi-threading is extensively used.
selecting a subset with tuples according Chapter 12 -
to a given condition. STRUCTURED QUERY LANGUAGE
(2) PROJECT (symbol : Π) PART -II
 The projection eliminates all attributes 1. Write a query that selects all students
of the input relation but those whose age is less than 18 in order wise.
mentioned in the projection list. Select * from Students where age < 19
(3) UNION (Symbol :∪) order by name;
 It includes all tuples that are in tables A 3. Write the difference between table
or in B. It also eliminates duplicates. constraint and column constraint?
 Set A Union Set B would be expressed as Column Table Constraint
A∪B Constraint
(4) SET DIFFERENCE ( Symbol : - ) Column constraint Table constraint
 The result of A – B, is a relation which apply only to apply to a group of
includes all tuples that are in A but not in individual column. one or more
B. columns.
(5) INTERSECTION (symbol : ∩) A ∩ B 5. What is the difference between SQL
 Defines a relation consisting of a set of and MySQL?
all tuple that are in both in A and B.  SQL is a language that helps to create
(6) PRODUCT OR CARTESIAN PRODUCT and operate relational databases.
(Symbol : X )  MySQL is a database management
 Cross product is a way of combining two system.
relations. PART -III
 The resulting relation contains, both 1. What is a constraint? Write short note
relations being combined. on Primary key constraint.
5. Explain the characteristics of DBMS. Constraint:
1. Data stored in table - Data is never  Constraint is a condition applicable on a
directly stored into the database. Data is field or set of fields.
stored into tables, created inside the Primary Constraint:
database.  The constraint declares a field as a
2. Reduced Redundancy - DBMS follows Primary key which helps to uniquely
Normalisation which divides the data in identify a record.
such a way that repetition is minimum.  The primary key does not allow NULL
3.Data Consistency - On live data, it is values
being continuously updated and added, 3. Write any three DDL commands. /
maintaining the consistency of data can Write a short note on (i) Alter (ii)
become a challenge. But DBMS handles it Truncate (iii) Drop.
by itself. (i) Alter:
4. Support Multiple user and Concurrent  The alter command is used to alter the
Access - DBMS allows multiple users to table structure.
work on it at the same time and still  Syntax:
manages to maintain the data consistency. ALTER TABLE <table-name> ADD
5.Query Language - DBMS provides users <column-name><data type><size>;
with a simple query language, using which (ii) Truncate:
data can be easily fetched, inserted, deleted
and updated in a database.
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 18 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
 The truncate command is used to delete  The constraint declares a field as a
all the rows from the table. Primary key which helps to uniquely
 Syntax: identify a record.
TRUNCATE TABLE table-name;  The primary key does not allow NULL
(iii) Drop: values.
 The drop command is used to remove a  Example:
table from the database. Create table student ( admno integer(4)
 If you drop a table, all the rows in the not null primary key, sname char(2) not
table is deleted and the table structure null, mark1 integer(2), mark2
is removed from the database.. integer(2));
 Syntax: DROP TABLE table-name; Default constraint:
4. Write the use of Save point command  The default constraint is used to assign
with an example. a default value for the field.
 The SAVEPOINT command is used to Check constraint:
temporarily save a transaction so that  This constraint helps to set a limit value
you can rollback to the point whenever placed for a field.
required.  When we define a check constraint on a
 The different states of our table can be single column, it allows only the
saved at anytime using different names restricted values on that field.
and the rollback to that state can be  Example:
done using the ROLLBACK command. Create table student ( admno integer(4)
 Syntax: not null primary key, sname char(2) not
SAVEPOINT savepoint_name; null, mark1 integer(2) (check<=70),
 Example: mark2 integer(2) (check<=90));
UPDATE Student SET Name =
‘Mini’ WHERE Admno=105;
SAVEPOINT A; 2. Consider the following employee table.
5. Write a SQL statement using DISTINCT Write SQL commands for the questions
keyword. (i) to (v).
SELECT DISTINCT Place FROM Student; EMP NAME DESIG PAY ALLO
PART -IV CODE WANCE
1. Write the different types of S1001 Hariha Supervisor 29000 12000
ran
constraints and their functions.
P1002 Shaji Operator 10000 5500
Constraint:
P1003 Prasad Operator 12000 6500
 Constraint is a condition applicable on a C1004 Manjim Clerk 8000 4500
field or set of fields. a
Types of constraints: M100 Rathee Mechanic 20000 7000
 Unique constraint 5 sh
 Primary key constraint (i) To display the details of all employees in
 Default constraint descending order of pay.
 Check constraint (ii) To display all employees whose
Unique constraint: allowance is between 5000 and 7000.
 This constraint ensures that no two (iii) To remove the employees who are
rows have the same value in the mechanic.
specified columns. (iv) To add a new row.
 Example: (v) To display the details of all employees
Create table student (admno who are operators.
integer NOT NULL UNIQUE); Answer:
Primary key constraint: (i) SELECT * from emp ORDERBY pay
DESC;

RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 19 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
(ii) SELECT * from emp WHERE allow 1. What is CSV File?
BETWEEN 5000.00 and 7000.00;  A CSV file is a human readable text file
(iii) DELETE from emp WHERE where each line has a number of fields,
desig='Mechanic'; separated by commas or some other
(iv) INSERT INTO emp (empcode, ename, delimiter.
Desig, Pay, Allow) VALUES (1006, 2. Mention the two ways to read a CSV
'Kumar', 'Manager', 30000.00, file using Python.
17000.00); 1. Use the csv module’s reader function
(v) SELECT * from emp WHERE 2. Use the DictReader class.
desig='Operator'; 3. Mention the default modes of the File.
3. What are the components of SQL?  Open a file for reading (r) is the default
Write the commands in each. mode.
Components of SQL: PART -III
 DML – Data Manipulation Language 1. Write a note on open( ) function of
 DDL – Data Definition Language python. What is the difference
 DCL – Data Control Language between the two methods?
 TCL – Transaction Control Language  Python has a built-in function open()
 DQL – Data Query Language to open a file.
DML – Data Manipulation Language:  This function returns a file object,
 INSERT, DELETE, UPDATE. also called a handle, as it is used to
DDL – Data Definition Language: read or modify the file accordingly.
 CREATE, ALTER, DROP,  For Example
TRUNCATE. f = open("sample.txt")
DCL - Data Control Language: f=open('c:\\pyprg\\ch13sample5.csv')
 GRANT, REVOKE 5. What is the difference between reader()
TCL – Transactional Control Language: and DictReader() function?
 COMMIT, ROLL BACK, SAVE POINT reader( ) DictReader( )
DQL – Data Query Language: The reader DictReader works by
 SELECT function is reading the first line
designed to take of the CSV and using
4. Construct the following SQL
each line of the file each comma
statements in the student table-
and make a list of separated value in
(i) SELECT statement using GROUP BY
all columns. this line as a
clause.
dictionary key.
(ii) SELECT statement using ORDER BY
PART -IV
clause.
1. Differentiate Excel file and CSV file.
Answer:
Excel CSV
SELECT * FROM Student ORDER BY Name;
Excel is a binary file CSV format is a
SELECT Gender, count(*) FROM Student
that holds plain text format
GROUP BY Gender;
information about with a series of
5. Write a SQL statement to create a all the worksheets values separated
table for employee having any five fields in a file, including by commas.
and create a table constraint for the both content and
employee table. formatting
CREATE TABLE Employee (Empno XLS files can only CSV can be opened
integer(4) NOT NULL, EmpName varchar be read by with any text editor
(20) NOT NULL, Gender char (1), Age applications that in Windows like
integer(2), Dept varchar(10), PRIMARY have been notepad, MS Excel,
KEY (Empno)); especially written to OpenOffice, etc.
read their format
Chapter 13 - PYTHON AND CSV FILES
PART -II
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 20 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
Excel is a CSV is a format for 4. Within the header and each record,
spreadsheet that saving tabular there may be one or more fields,
saves files into its information into a separated by commas.
own proprietary delimited text file 5. Each field may or may not be enclosed
format viz. xls or with extension .csv in double quotes.
xlsx 6. Fields containing line breaks (CRLF),
Excel consumes Importing CSV files double quotes, and commas should be
more memory while can be much enclosed in double-quotes.
importing data faster, and it also 7. If double-quotes are used to enclose
consumes less fields, then a double-quote appearing
memory inside a field must be preceded with
another double quote.
2. Tabulate the different mode with its CHAPTER 14
meaning. IMPORTING C++ PROGRAMS IN PYTHON
Mode – Description
PART - II
‘r’ - Open a file for reading. (default) 2. Differentiate compiler and interpreter.
‘w’ - Open a file for writing.
Compiler Interpreter
‘x’ - Open a file for exclusive creation.
Translate Directly executes the
‘a’ - Open for appending at the end of the
instructions into instructions in the
file without truncating it.
effect machine source programming
‘t’ - Open in text mode. (default)
code. language.
‘b’ - Open in binary mode.
3. Write the expansion of (i) SWIG (ii)
‘+’ - Open a file for updating
MinGW
3. Write the different methods to read a
(i) SWIG - Simplified Wrapper Interface
File in Python.
Generator- Both C and C++.
 You can read the contents of CSV file
(ii) MinGW - Minimalist GNU for Windows.
with the help of csv.reader() method.
4. What is the use of modules?
 The reader function is designed to
 Using the module name we can access
take each line of the file and make a
the functions defined inside the module.
list of all columns.
 The dot (.) operator is used to access the
 Using this method one can read data
functions.
from csv files of different formats like
PART - III
quotes (" "), pipe (|) and comma (,).
1. Differentiate PYTHON and C++
 The syntax for csv.reader()
Python C++
sv.reader(fileobject,delimiter,fmtparams)
Python is typically an C++ is typically a
Methods to read a file
"interpreted" language "compiled" language
1. CSV file - data with default delimiter
C++ is compiled
comma (,) Python is a dynamic-
statically typed
2. CSV file - data with Space at the typed language
language
beginning
3. CSV file - data with quotes Data type is not Data type is required
4. CSV file - data with custom Delimiters required while while declaring
5. Write the rules to be followed to declaring variable variable
format the data in a CSV file. It can act both as
It is a general purpose
1. Each record is to be located on a scripting and general
language
separate line, delimited by a line break purpose language
by pressing enter key. 3. What is MinGW? What is its use?
2. The last record in the file may or may not  MinGW refers to a set of runtime header
have an ending line break. files, used in compiling and linking the
3. There may be an optional header line code of C, C++ and FORTRAN to be run
appearing as the first line of the file with on Windows Operating System.
the same format as normal record lines.
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 21 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
 MinGW allows to compile and execute  os.system( ): Execute the C++ compiling
C++ program dynamically through command in the shell
Python program using g++. (iii) Python getopt module:
4. Identify the module, operator,  The getopt module of Python helps you
definition name for the following to parse (split) command-line options
welcome.display( ) and arguments.
 Module : welcome  getopt.getopt method: This method
 Operator : dot( . ) parses command-line options and
 Definition name : display( ) parameter list.
5. What is sys.argv? What does it  The syntax: <opts>,<args> =
contain? getopt.getopt (argv,
 sys.argv is the list of command-line options, [long_options])
arguments passed to the Python
program. CHAPTER 15
 Argv contains all the items that come DATA MANIPULATION THROUGH SQL
along via the command-line input, it's Part - II
basically an array holding the 1. Mention the users who uses the
command-line arguments of the Database.
program. Users of database can be human users,
PART - IV other programs or applications.
2. Explain each word of the following 2. Which method is used to connect a
command. database? Give an example.
Python <filename.py> -<i> <C++  The connect( ) method is used to
filename without cpp extension> connect a database.
Python - The keyword to execute the  Example: connection =
Python program from command line sqlite3.connect("Academy.db")
<filename.py> - Name of the Python 3. What is the advantage of declaring a
program to executed column as “INTEGER PRIMARY KEY”
-<i> - The input mode If a column of a table is declared to be an
<C++ filename without cpp extension> - INTEGER PRIMARY KEY, then whenever a
The name of C++ file to be compiled and NULL will be used as an input for this
executed column, the NULL will be automatically
3. What is the purpose of sys, os, getopt converted into an integer which will one
module in Python. Explain larger than the highest value so far used in
(i) Python’s sys module: that column.
 This module provides access to some 4. Write the command to populate record
variables used by the interpreter and to in a table. Give an example.
functions that interact strongly with the  To populate (add record) the table
interpreter. "INSERT" command is passed to SQLite.
 sys.argv is the list of command-line  Example:
arguments passed to the Python sql_command = """INSERT INTO Student
program. VALUES (NULL, "Akshay", "B",
(ii) Python's OS Module: "M","87.8", "2001-12-12");"""
 The OS module in Python provides a way cursor.execute(sql_ command)
of using operating system dependent 5. Which method is used to fetch all rows
functionality. from the database table?
 The functions that the OS module allows  The fetchall() method is used to fetch
you to interface with the Windows all rows from the database table.
operating system where Python is Part - III
running on. 1. What is SQLite? What is it advantage?

RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 22 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
 SQLite is a simple relational  Steps to use SQLite:
database system, which saves its Step 1: Import sqlite3
data in regular data files or even in Step 2: Create a connection using
the internal memory of the computer. connect( ) method and pass the name of
 Advantages: the database File
1. It is designed to be embedded in Step 3: Set the cursor object cursor =
applications, instead of using a connection. cursor( )
separate database server program  A control structure used to traverse
such as MySQLor Oracle. and fetch the records of the
2. SQLite is fast, rigorously tested, and database.
flexible, making it easier to work. 4. Write a Python script to create a table
Python has a native library for called ITEM with following
SQLite. specification.
2. Mention the difference between Add one record to the table.
fetchone() and fetchmany() Name of the database: ABC
fetchone( ) fetchmany( ) Name of the table: Item
The fetchone () method fetchmany() Column name and specification:
returns the next row of method that Answer:
a query result set or returns the next import sqlite3
None in case there is no number of rows (n) connection = sqlite3.connect
row left. of the result set ("ABC.db")
4. Read the following details. Based on cursor = connection.cursor()
that write a python script to display sql_command = """
department wise records CREATE TABLE item (
database name: organization.db Icode INTEGER PRIMARY KEY ,
Table name: Employee Item_Name VARCHAR(25), Rate
Columns in the table: Eno, DECIMAL(5, 2));"""
EmpName, Esal, Dept cursor.execute(sql_command)
Answer: sql_command = """INSERT INTO Item
import sqlite3 (Icode, Item_Name, Rate)
connection = VALUES (1008,
sqlite3.connect("organization.db") "Monitor",15000.00);"""
cursor = connection.cursor() cursor.execute(sql_command)
cursor.execute("SELECT Eno, connection.commit()
EmpName, Esal, Dept FROM Employee connection.close()
Group BY Dept") print("ITEM TABLE CREATED")
result = cursor.fetchall()
print(*result,sep="\n") Chapter 16 - DATA VISUALIZATION
PART - IV PART – II
1. Write in brief about SQLite and the 1. Define: Data Visualization.
steps used to use it.  Data Visualization is the graphical
 SQLite is a simple relational database representation of information and data.
system, which saves its data in regular 2. List the general types of data
data files or even in the internal memory visualization.
of the computer. 1) Charts 2) Tables 3) Graphs
 It is designed to be embedded in 4) Maps 5) Infographics 6) Dashboards
applications, instead of using a separate 3. List the types of Visualizations in
database server program such as Matplotlib.
MySQL or Oracle. 1) Line plot 2) Scatter plot 3) Histogram
 SQLite is fast, rigorously tested, and 4) Box plot 5) Bar chart and 6) Pie chart
flexible, making it easier to work. Python 4. How will you install Matplotlib?
has a native library for SQLite.  Install matplotlib using pip.
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 23 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY
HIGHER SECONDARY- SECOND YEAR - COMPUTER SCIENCE
 Pip is a management software for  A Line Chart is often used to visualize a
installing python packages. trend in data over intervals of time
PART - III (ii) Bar Chart
1. Draw the output for the following data  A BarPlot (or BarChart) is one of the
visualization plot. most common type of plot.
import matplotlib.pyplot as plt  It shows the relationship between a
plt.bar([1,3,5,7,9],[5,2,7,8,2], numerical variable and a categorical
label="Example one") variable.
plt.bar([2,4,6,8,10],[8,6,2,5,6],  Bar chart represents categorical data
label="Example two", color='g') with rectangular bars.
plt.legend() (iii) Pie Chart
plt.xlabel('bar number')  Pie Chart is probably one of the most
plt.ylabel('bar height') common type of chart.
plt.title('Epic Graph\nAnother Line! Whoa')  It is a circular graphic which is divided
plt.show() into slices to illustrate numerical
Solution: proportion.
 The point of a pie chart is to show the
relationship of parts out of a whole.
 To make a Pie Chart with Matplotlib, we
can use the plt.pie() function.
2. Explain the various buttons in a
matplotlib window.
 Home Button:
The Home Button will help once you have
begun navigating your chart.
 Forward/Back buttons:
2. Write any three uses of data These buttons can be used like the Forward
visualization. and Back buttons in your browser.
1. Data Visualization help users to analyze  Pan Axis:
and interpret the data easily. This cross-looking button allows you to
2. It makes complex data understandable click it, and then click and drag your graph
and usable. around.
3. Various Charts in Data Visualization  Zoom:
helps to show relationship in the data for The Zoom button lets you click on it, then
one or more variables. click and drag a square that you would like
3. Write the coding for the following: to zoom into specifically.
a. To Install PIP in your PC.  Configure Subplots:
 Python –m pip install –U pip This button allows you to configure various
b. To Check the version of PIP installed in spacing options with your figure and plot.
your PC.  Save Figure:
 pip --version This button will allow you to save your
c. To list the packages in matplotlib. figure in various forms.
 pip list 3. Explain the purpose of the following
PART - IV functions:
1. Explain in detail the types of pyplots a. plt.xlabel - Assign labels to x axis
using Matplotlib.
(i) Line Chart b. plt.ylabel - Assign labels to y axis
 A Line Chart or Line Graph is a type of c. plt.title - Assign plot title
chart which displays information as a d. plt.legend() - Assign default legend
series of data points called ‘markers’ e. plt.show() - Used to invoke graph
connected by straight line segments. window
RESOURCE PERSONS:
SOUNDARAPANDIAN S, Instructor in Computer Science
JEEVANANDAM GBHS, KARAMANIKUPPAM, PDY 24 D.KAYALVIZHI, ICS
USHA D, Instructor in Computer Science ANNAI SIVAGAMI GGHSS, MUDALIARPET, PDY
VALLALAR GGHSS, LAWSPET, PDY

You might also like