Xii - CS Reudced Study Materials 2020-2021
Xii - CS Reudced Study Materials 2020-2021
Xii - CS Reudced Study Materials 2020-2021
S)
NAME
SUBJECT
TABLE OF CONTENTS
COMPUTER SCIENCE – II YEAR
1 FUNCTION
4 ALGORITHMIC STRATEGIES
6 CONTROL STRUCTURES
UNIT – II
CORE PYTHON
7 PYTHON FUNCTION
11 DATABASE CONCEPTS
UNIT – IV
DATABASE
12 STRUCTURED QUERY LANGUAGE(SQL)
CONCEPTS AND
MYSQL
13 PYTHON AND CSV FILES
1. FUNCTIONS
Section – A
Choose the best answer (1 Mark)
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?
6. Which of the following are mandatory to write the type annotations in the function definition?
(A) Curly braces (B) Parentheses (C) Square brackets (D) indentations
Section-B
Answer the following questions (2 Mark)
1. What is a subroutine?
Subroutines are the basic building blocks of computer programs.
Subroutines are small sections of code that are used to perform a particular task that can be used
repeatedly.
2. Define Function with respect to Programming language.
A function is a unit of code that is often defined within a greater code structure.
A function works on many kinds of inputs and produces a concrete output
3. Write the inference you get from X:=(78).
X:=(78) is a function definition.
Definitions bind values to names.
Hence, the value 78 bound to the name „X‟.
5. Which of the following is a normal function definition and which is recursive function definition?
i) let rec sum x y:
return x + y
Ans: Recursive Function
ii) let disp :
print „welcome‟
Ans: Normal Function
iii) let rec sum num:
if (num!=0) then return num + sum (num-1)
else
return num
Ans: Recursive Function
Section - D
Answer the following questions: (5 Mark)
Answer:
(requires: b>=0 )
(returns: a to the power of b)
let rec pow a b:=
if b=0 then 1
else a * pow a (b-1)
In the above function definition variable ‘ b’ is the parameter and the value passed to the variable
‘b’ is the argument.
We have not mentioned any types: (data types). This is called parameter without type.
In the above function definition the expression has type ‘int’, so the function's return type also be
‘int’ by implicit.
(requires: b> 0 )
(returns: a to the power of b )
let rec pow (a: int) (b: int) : int :=
if b=0 then 1
else a * pow b (a-1)
In this example we have explicitly annotating the types of argument and return type as ‘int’.
Here, when we write the type annotations for „a‟ and „b‟ the parantheses are mandatory.
This is the way passing parameter with type which helps the compiler to easily infer them.
2. DATA ABSTRACTION
Section – A
Choose the best answer (1 Mark)
1. Which of the following functions that build the abstract data type ?
2. Which of the following functions that retrieve information from the data type?
Section-B
Answer the following questions (2 Mark)
1. What is abstract data type?
Abstract Data type (ADT) is a type or class for objects whose behavior is defined by a set of value
and a set of operations.
2. Differentiate constructors and selectors.
CONSTRUCTORS SELECTORS
Constructors are functions that build the Selectors are functions that retrieve
abstract data type. information from the data type.
Section-C
Answer the following questions (3 Mark)
3. Identify Which of the following are constructors and selectors?
Section - D
Answer the following questions: (5 Mark)
1. How will you facilitate data abstraction. Explain it with suitable example.
Data abstraction is supported by defining an abstract data type (ADT), which is a collection of
constructors and selectors.
To facilitate data abstraction, you will need to create two types of functions:
Constructors
Selectors
a) Constructor:
Constructors are functions that build the abstract data type.
Constructors create an object, bundling together different pieces of information.
For example, say you have an abstract data type called city.
This city object will hold the city‟s name, and its latitude and longitude.
To create a city object, you‟d use a function like city = makecity (name, lat, lon).
Here makecity (name, lat, lon) is the constructor which creates the object city.
b) Selectors:
Selectors are functions that retrieve information from the data type.
Selectors extract individual pieces of information from the object.
To extract the information of a city object, you would use functions like
getname(city)
getlat(city)
getlon(city)
These are the selectors because these functions extract the information of the city object.
3. SCOPING
Section – A
Choose the best answer (1 Mark)
1. Which of the following refers to the visibility of variables in one part of a program to another part of
the same program.
(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) Local Scope (B) Global scope (C) Module scope (D) Function Scope
Section-B
Answer the following questions (2 Mark)
1. What is a scope?
Scope refers to the visibility of variables, parameters and functions in one part of a program to
another part of the same program.
2. Why scope should be used for variable. State the reason.
The scope should be used for variables because; it limits a variable's scope to a single definition.
That is the variables are visible only to that part of the code.
Example:
3. What is Mapping?
Namespaces are containers for mapping names of variables to objects (name : = object).
Example: a:=5
Here the variable „a‟ is mapped to the value „5‟.
Section-C
Answer the following questions (3 Mark)
1. Define Local scope with an example.
On execution of the above code the variable a displays the value 7, because it is defined and
available in the local scope.
2. Define Global scope with an example.
A variable which is declared outside of all the functions in a program is known as global variable.
Global variable can be accessed inside or outside of all the functions in a program.
Example:
On execution of the above code the variable a which is defined inside the function displays the value
7 for the function call Disp() and then it displays 10, because a is defined in global scope.
3. Define Enclosed scope with an example.
A variable which is declared inside a function which contains another function definition with in it,
the inner function can also access the variable of the outer function. This scope is called enclosed
scope.
When a compiler or interpreter searches for a variable in a program, it first search Local, and then
search Enclosing scopes.
In the above example Disp1() is defined within Disp(). The variable „a‟ defined in Disp() can be
even used by Disp1() because it is also a member of Disp().
5. Identify the scope of the variables in the following pseudo code and write its output.
color:= Red
mycolor():
b:=Blue
myfavcolor():
g:=Green
print color, b, g
myfavcolor()
print color, b
mycolor()
print color
OUTPUT:
Red Blue Green
Red Blue
Red
10 Visit :http://www.youtube.com/c/CSKNOWLEDGEOPENER CS KNOWLEDGE OPENER
J. BASKARAN M.Sc., B.Ed. (C.S) KNOWLEDGE OPENING & KNOWLEDGE TRANSFORMATION J. ILAKKIA M.Sc., M.Phil., B.Ed. (C.S)
Scope of Variables:
Variables Scope
Color:=Red Global
b:=Blue Enclosed
G:=Green Local
Section - D
Answer the following questions: (5 Mark)
1. Explain the types of scopes for variable or LEGB rule with example.
SCOPE:
Scope refers to the visibility of variables, parameters and functions in one part of a program to another
part of the same program.
TYPES OF VARIABLE SCOPE:
Local Scope
Enclosed Scope
Global Scope
Built-in Scope
LEGB RULE:
The LEGB rule is used to decide the order in which the scopes are to be searched for scope resolution.
i) LOCAL SCOPE:
Local scope refers to variables defined in current function.
A function will always look up for a variable name in its local scope.
Only if it does not find it there, the outer scopes are checked.
Example:
On execution of the above code the variable a displays the value 7, because it is defined and
available in the local scope.
ii) ENCLOSED SCOPE:
A variable which is declared inside a function which contains another function definition with in it,
the inner function can also access the variable of the outer function. This scope is called enclosed
scope.
When a compiler or interpreter searches for a variable in a program, it first search Local, and then
search Enclosing scopes.
In the above example Disp1() is defined within Disp(). The variable „a‟ defined in Disp() can be
even used by Disp1() because it is also a member of Disp().
iii) GLOBAL SCOPE:
A variable which is declared outside of all the functions in a program is known as global variable.
Global variable can be accessed inside or outside of all the functions in a program.
Example:
On execution of the above code the variable a which is defined inside the function displays the value
7 for the function call Disp() and then it displays 10, because a is defined in global scope.
iv) BUILT-IN-SCOPE:
The built-in scope has all the names that are pre-loaded into the program scope when we start the
compiler or interpreter.
Any variable or module which is defined in the library functions of a programming language has
Built-in or module scope.
4. ALGORITHMIC STRATEGIES
Section – A
Choose the best answer (1 Mark)
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) Quick sort (C) Merge sort (D) Selection sort
6. Which of the following is not a stable sorting algorithm?
(A) Insertion sort (B) Selection sort (C) Bubble sort (D) Merge sort
Section-B
Answer the following questions (2 Mark)
1. What is an Algorithm?
Pseudo code is a methodology that allows the programmer to represent the implementation of an
algorithm.
It has no syntax like programming languages and thus can't be compiled or interpreted by the
computer.
3. Who is an Algorist?
Input
Output
Finiteness
Definiteness
Effectiveness
Correctness
Simplicity
Unambiguous
Feasibility
Portable
Independent
Section - D
Answer the following questions: (5 Mark)
Characteristics Meaning
Input Zero or more quantities to be supplied.
Output At least one quantity is produced.
LINEAR SEARCH:
Linear search also called sequential search is a sequential method for finding a particular value in a list.
This method checks the search element with each element in sequence until the desired element is
found or the list is exhausted.
Pseudo code:
If the values do not match, move on to the next array element. If no match is found, display the
search element not found.
3. If no match is found, display the search element not found.
Example:
To search the number 25 in the array given below, linear search will go step by step in a sequential
order starting from the first element in the given array.
if the search element is found that index is returned otherwise the search is continued till the last
index of the array.
index 0 1 2 3 4
values 10 12 20 25 30
Snippet:
Input: values[]={10,12,20,25,30}
Target=25
Output:
3
3. What is Binary search? Discuss with example.
BINARY SEARCH:
Binary search also called half-interval search algorithm.
It finds the position of a search element within a sorted array.
The binary search algorithm can be done as divide-and-conquer search algorithm and executes in
logarithmic time.
Pseudo code for Binary search:
1. Start with the middle element:
a) If the search element is equal to the middle element of the array, then return the index of the
middle element.
b) If not, then compare the middle element with the search value,
c) If (Search element > number in the middle index), then select the elements to the right side
of the middle index, and go to Step-1.
16 Visit :http://www.youtube.com/c/CSKNOWLEDGEOPENER CS KNOWLEDGE OPENER
J. BASKARAN M.Sc., B.Ed. (C.S) KNOWLEDGE OPENING & KNOWLEDGE TRANSFORMATION J. ILAKKIA M.Sc., M.Phil., B.Ed. (C.S)
d) If (Search element < number in the middle index), then select the elements to the left side of
the middle index, and start with Step-1.
2. When a match is found, display success message with the index of the element matched.
3. If no match is found for all comparisons, then display unsuccessful message.
The array is being sorted in the given example and it is suitable to do the binary search algorithm.
Let us assume that the search element is 60 and we need to search the location or index of search
element 60 using binary search.
First, we find index of middle element of the array by using this formula :
Compare the value stored at index 4 with target value, which is not match with search element. As
the search value 60 > 50.
Now we change our search range low to mid + 1 and find the new mid value as index 7.
Element not found because the value in index 7 is greater than search value . ( 80 > 60)
So, the search element must be in the lower part from the current mid value location
Now we change our search range low to mid - 1 and find the new mid value as index 5
Now we compare the value stored at location 5 with our search element.
We found that it is a match.
It compares each pair of adjacent elements and swaps them if they are in the unsorted order.
This comparison and passed to be continued until no swaps are needed, which shows the values in
an array is sorted.
It is named so becase, the smaller elements "bubble" to the top of the list.
It is too slow and less efficient when compared to other sorting methods.
Pseudo code
1. Start with the first element i.e., index = 0, compare the current element with the next element of the
array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next or right side of the element, move to the next element.
4. Go to Step 1 and repeat until end of the index is reached.
Example:
Consider an array with values {15, 11, 16, 12, 14, 13}
Below, we have a pictorial representation of how bubble sort.
A) # B) & C) @ D) $
5. This symbol is used to print more than one item on a single line.
Section-B
Answer the following questions (2 Mark)
1. What are the different modes that can be used to test Python Program ?
In Python, programs can be written in two ways namely Interactive mode and Script mode.
Interactive mode allows us to write codes in Python command prompt ( >>> ).
Script mode is used to create and edit python source file with the extension .py
2. Write short notes on Tokens.
Python breaks each logical line into a sequence of elementary lexical components known as Tokens.
The normal token types are ,
1) Identifiers,
2) Keywords,
3) Operators,
4) Delimiters and
5) Literals.
3. What are the different operators that can be used in Python ?
Operators are special symbols which represent computations, conditional matching in programming.
Operators are categorized as Arithmetic, Relational, Logical, Assignment and Conditional.
Example :
The input() function helps to enter data at run time by the user
The output function print() is used to display the result of the program on the screen after execution.
1) print() function
Example:
“Prompt string” in the syntax is a message to the user, to know what input can be given.
If a prompt string is used, it is displayed on the monitor; the user can provide expected data from
the input device.
The input( ) takes typed data from the keyboard and stores in the given variable.
If prompt string is not given in input( ), the user will not know what is to be typed as input.
Example:
In Example 1 input() using prompt string takes proper input and produce relevant output.
In Example 2 input() without using prompt string takes irrelevant input and produce unexpected
output.
So, to make your program more interactive, provide prompt string with input( ).
Input() using Numerical values:
The input ( ) accepts all data as string or characters but not as numbers.
The int( ) function is used to convert string data as integer data explicitly.
Example:
4) Delimiters
Python uses the symbols and symbol combinations as delimiters in expressions, lists, dictionaries and
strings.
Following are the delimiters.
5) Literals
Literal is a raw data given in a variable or constant.
In Python, there are various types of literals. They are,
1) Numeric Literals consists of digits and are immutable
2) String literal is a sequence of characters surrounded by quotes.
3) Boolean literal can have any of the two values: True or False.
6. CONTROL STRUCTURES
Section – A
Choose the best answer (1 Mark)
1. How many important control structures are there in Python?
A) 3 B) 4 C) 5 D) 6
statements-block 1
else:
statements-block 2
A) ; B) : C) :: D) !
Section-B
Answer the following questions (2 Mark)
1. List the control structures in Python.
Syntax:
if <condition>:
statements-block 1
else:
statements-block 2
4. Define control structure.
A program statement that causes a jump of control from one part of the program to another is called
control structure or control statement.
Where,
Section-C
Answer the following questions (3 Mark)
1. Write a program to display
A
AB
ABC
ABCD
ABCDE
CODE:
for i in range(65, 70):
for j in range(65, i+1):
print(chr(j), end= „ „)
print(end=‟\n‟)
i+=1
OUTPUT
A
AB
ABC
ABCD
ABCDE
2. Write note on if..else structure.
The if .. else statement provides control to check the true block as well as the false block.
if..else statement thus provides two possibilities and the condition determines which BLOCK is to be
executed.
Syntax:
if <condition>:
statements-block 1
else:
statements-block 2
3. Using if..else..elif statement write a suitable program to display largest of 3 numbers.
CODE:
n1= int(input("Enter the first number:"))
n2= int(input("Enter the second number:"))
Syntax:
while <condition>:
statements block 1
[else:
statements block2]
5. List the differences between break and continue statements.
break continue
The break statement terminates the loop The Continue statement is used to skip the
containing it. remaining part of a loop and
Control of the program flows to the statement Control of the program flows start with next
immediately after the body of the loop. iteration.
Syntax: Syntax:
break continue
Section - D
Answer the following questions: (5 Mark)
for i in range(2,10,2):
print (i,end=' ')
else:
print ("\nEnd of the loop")
Output:
2468
End of the loop
2. Write a detail note on if..else..elif statement with suitable example.
When we need to construct a chain of if statement(s) then „elif‟ clause can be used instead of „else‟.
„elif‟ clause combines if..else-if..else statements to one if..elif…else.
if <condition-1>:
statements-block 1
elif <condition-2>:
statements-block 2
else:
statements-block n
In the syntax of if..elif..else mentioned above, condition-1 is tested if it is true then statements-block1
is executed.
Otherwise the control checks condition-2, if it is true statements-block2 is executed and even if it fails
statements-block n mentioned in else part is executed.
Example:
m1=int (input(“Enter mark in first subject : ”))
m2=int (input(“Enter mark in second subject : ”))
avg= (m1+m2)/2
if avg>=80:
print (“Grade : A”)
elif avg>=70 and avg<80:
print (“Grade : B”)
elif avg>=60 and avg<70:
print (“Grade : C”)
elif avg>=50 and avg<60:
print (“Grade : D”)
else:
print (“Grade : E”)
Output :
Enter mark in first subject : 34
Enter mark in second subject : 78
Grade : D
CODE:
lower=int(input("Enter the lower limit for the range:"))
upper=int(input("Enter the upper limit for the range:"))
for i in range(lower,upper+1):
if(i%2!=0):
print(i,end=" ")
Output:
7. PYTHON FUNCTIONS
Section – A
Choose the best answer (1 Mark)
1. A named blocks of code that are designed to do one specific job is called as
(I) In Python, you don‟t have to mention the specific data types while defining function.
10. Which of the following keyword is used to define the function testpython(): ?
Section-B
Answer the following questions (2 Mark)
1. What is function?
Functions are named blocks of code that are designed to do one specific job.
Types of Functions are User defined, Built-in, lambda and recursion.
Function blocks begin with the keyword “def ” followed by function name and parenthesis ().
2. Write the different types of function.
TYPES OF FUNCTION:
Scope of variable refers to the part of the program, where it is accessible, i.e., area where you can refer
(use) it.
Scope holds the current set of variables and their values.
The two types of scopes are- local scope and global scope.
5. Define global scope.
• A variable with local scope can be accessed only within the function/block that it is created in.
• When a variable is created inside the function/block, the variable becomes local to it.
• A local variable only exists while the function is executing.
Section - D
Answer the following questions: (5 Mark)
Output:
0
Global Scope
• A variable, with global scope can be used anywhere in the program.
• It can be created by defining a variable outside the scope of any function/block.
Rules of global Keyword
The basic rules for global keyword in Python are:
• When we define a variable outside a function, it‟s global by default. You don‟t have to use global
keyword.
• We use global keyword to read and write a global variable inside a function.
• Use of global keyword outside a function has no effect
Use of global Keyword
• Without using the global keyword we cannot modify the global variable inside the function but we
can only access the global variable.
Example:
x=0 # global variable
def add():
global x
x=x+5 # increment by 2
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 #value of x changed outside the function
4. Write a Python code to find the L.C.M. of two numbers.
CODE:
x=int(input("Enter first number:"))
y=int(input("Enter second number:"))
if x>y:
min=x
else:
min=y
while(1):
if((min%x == 0) and (min % y == 0)):
print("LCM is:",min)
break
min=min+1
OUTPUT:
Enter first number:2
Enter second number:3
LCM is: 6
str1="TamilNadu"
print(str1[::-1])
str1[7] = "-"
5. Strings in python:
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
(a) Positive (b) Negative (c) Both (a) and (b) (d) Either (a) or (b)
Section-B
Answer the following questions (2 Mark)
1. What is String?
str1 = “School”
print(str1*3)
OUTPUT:
str[start:end]
Section-C
Answer the following questions (3 Mark)
1. Write a Python program to display the given pattern
COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C
CODE:
str="COMPUTER"
index=len(str)
for i in str:
print(str[:index])
index-=1
3. What will be the output of the given python program?
CODE:
str1 = "welcome"
str3=str1[:2]+str2[len(str2)-2:]
print(str3)
OUTPUT:
weol
The format( ) function used with strings is very powerful function used for formatting strings.
The curly braces { } are used as placeholders or replacement fields which get replaced along with
format( ) function.
EXAMPLE:
num1=int (input("Number 1: "))
num2=int (input("Number 2: "))
print ("The sum of { } and { } is { }".format(num1, num2,(num1+num2)))
OUTPUT:
Number 1: 34
Number 2: 54
The sum of 34 and 54 is 88
Section - D
Answer the following questions: (5 Mark)
3. Which of the following function is used to count the number of elements in a list?
6. Which of the following Python function can be used to add more than one element within an
Existing list?
(a) append() (b) append_more() (c)extend() (d) more()
7. What will be the result of the following Python code?
(c) To know the data type of python object. (d) To create a list.
10. Let setA={3,6,9}, setB={1,3,9}. What will be the result of the following snippet?
print(setA|setB)
11. Which of the following set operation includes all the elements that are in two sets but not the one that
are common to two sets?
Section-B
Answer the following questions (2 Mark)
1. What is List in Python?
A list is an ordered collection of values enclosed within square brackets [ ] also known as a “sequence
data type”.
Each value of a list is called as element.
Elements can be a numbers, characters, strings and even the nested lists.
Syntax: Variable = [element-1, element-2, element-3 …… element-n]
2. How will you access the list elements in reverse order?
Python enables reverse or negative indexing for the list elements.
A negative index can be used to access an element in reverse order.
Thus, python lists index in opposite order.
The python sets -1 as the index value for the last element in list and -2 for the preceding element and so
on.
This is called as Reverse Indexing.
3. What will be the value of x in following python code?
List1=[2,4,6,[1,3,5]]
x=len(List1)
print(x)
OUTPUT:
Syntax:
Tuple_Name = (E1, E2, E2 ……. En) # Tuple with n number elements
Tuple_Name = E1, E2, E3 ….. En # Elements of a tuple without parenthesis
6. What is set in Python?
In python, a set is another type of collection data type.
A Set is a mutable and an unordered collection of elements without duplicates or repeated element.
This feature used to include membership testing and eliminating duplicate elements.
Section-C
Answer the following questions (3 Mark)
1. What are the advantages of Tuples over a list?
The elements of a list are changeable (mutable) whereas the elements of a tuple are unchangeable
(immutable), this is the key difference between tuples and list.
The elements of a list are enclosed within square brackets. But, the elements of a tuple are enclosed by
paranthesis.
Iterating tuples is faster than list.
3. What will be the output of the following code?
print(list)
Set Operations:
(i) Union: It includes all elements from two or more sets.
(ii) Intersection: It includes the common elements in two sets.
(iii) Difference: It includes all elements that are in first set (say set A) but not in the second set (say set
B).
iv) Symmetric difference: It includes all the elements that are in two sets (say sets A and B) but not the
one that are common to two sets.
Section - D
Answer the following questions: (5 Mark)
1. What the different ways to insert an element in a list. Explain with suitable example.
Inserting elements in a list using insert():
The insert ( ) function helps you to include an element at your desired position.
The insert( ) function is used to insert an element at any position of a list.
Syntax:
List.insert (position index, element)
Example:
>>> MyList=[34,98,47,'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan' ]
>>> MyList.insert(3, 'Ramakrishnan')
>>> print(MyList)
Output: [34, 98, 47, 'Ramakrishnan', 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']
In the above example, insert( ) function inserts a new element „Ramakrishnan‟ at the index value 3, ie.
th
at the 4 position.
While inserting a new element, the existing elements shifts one position to the right.
Adding more elements in a list using append():
The append( ) function is used to add a single element in a list.
But, it includes elements at the end of a list.
Syntax:
List.append (element to be added)
Example:
>>> Mylist=[34, 45, 48]
>>> Mylist.append(90)
>>> print(Mylist)
Output: [34, 45, 48, 90]
Adding more elements in a list using extend():
The extend( ) function is used to add more than one element to an existing list.
In extend( ) function, multiple elements should be specified within square bracket as arguments of the
function.
Syntax:
List.extend ( [elements to be added])
Example:
>>> Mylist=[34, 45, 48]
>>> Mylist.extend([71, 32, 29])
>>> print(Mylist)
Output: [34, 45, 48, 90, 71, 32, 29]
2. What is the purpose of range( )? Explain with an example.
range():
The range( ) is a function used to generate a series of values in Python.
Using range( ) function, you can create list with series of values.
The range( ) function has three arguments.
Output:
1
2
3
4
5
6
7
8
9
10
Using the range( ) function, you can create a list with series of values.
To convert the result of range( ) function into list, we need one more function called list( ).
The list( ) function makes the result of range( ) as a list.
Syntax:
List_Varibale = list ( range ( ) )
Example :
>>> Even_List = list(range(2,11,2))
>>> print(Even_List)
Output: [2, 4, 6, 8, 10]
In the above code, list( ) function takes the result of range( ) as Even_List elements.
Thus, Even_List list has the elements of first five even numbers.
3. What is nested tuple? Explain with an example.
Tuple:
Tuples consists of a number of values separated by comma and enclosed within parentheses.
Tuple is similar to list, values in a list can be changed but not in a tuple.
Nested Tuples:
In Python, a tuple can be defined inside another tuple; called Nested tuple.
In a nested tuple, each tuple is considered as an element.
The for loop will be useful to access all the elements in a nested tuple.
Example:
Toppers = (("Vinodini", "XII-F", 98.7), ("Soundarya", "XII-H", 97.5), ("Tharani", "XII-F", 95.3),
("Saisri", "XII-G", 93.8))
for i in Toppers:
print(i)
Output:
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F', 95.3)
('Saisri', 'XII-G', 93.8)
4. Explain the different set operations supported by python with suitable example.
A Set is a mutable and an unordered collection of elements without duplicates.
Set Operations:
The set operations such as Union, Intersection, difference and Symmetric difference.
(i) Union:
It includes all elements from two or more sets.
The operator | is used to union of two sets.
The function union( ) is also used to join two sets in python.
Example:
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
U_set=set_A|set_B
print(U_set)
Output:
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}
(ii) Intersection:
It includes the common elements in two sets.
The operator & is used to intersect two sets in python.
The function intersection( ) is also used to intersect two sets in python.
Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B)
Output:
{'A', 'D'}
(iii) Difference:
It includes all elements that are in first set (say set A) but not in the second set (say set B).
The minus (-) operator is used to difference set operation in python.
The function difference( ) is also used to difference operation.
Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B)
Output:
{2, 4}
Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B)
Output:
{2, 4, 'B', 'C'}
(a) class class_name (b) class class_name<> (c) class class_name: (d) class class_name[ ]
Section-B
Answer the following questions (2 Mark)
1. What is class?
class Sample:
__num=10
def disp(self):
print(self.__num)
S=Sample()
S.disp()
print(S.__num)
OUTPUT:
>>>
10
line 7, in <module>
print(S.__num)
AttributeError: 'Sample' object has no attribute '__num'
“init” is a special function begin and end with double underscore in Python act as a Constructor.
Constructor function will automatically executed when an object of a class is created.
General format:
<statements>
def __del__(self):
<statements>
Section-C
Answer the following questions (3 Mark)
1. What are class members? How do you define it?
Variables defined inside a class are called as “Class Variable” and functions are called as “Methods”.
Class variable and methods are together known as members of the class.
The class members should be accessed through objects or instance of class.
A class can be defined anywhere in a Python program.
SYNTAX FOR DEFINING A CLASS:
class class_name:
statement_1
statement_2
…………..
…………..
statement_n
2. Write a class with two private class variables and print the sum using a method.
CODE:
class Sample:
def __init__(self,n1,n2):
56 Visit :http://www.youtube.com/c/CSKNOWLEDGEOPENER CS KNOWLEDGE OPENER
J. BASKARAN M.Sc., B.Ed. (C.S) KNOWLEDGE OPENING & KNOWLEDGE TRANSFORMATION J. ILAKKIA M.Sc., M.Phil., B.Ed. (C.S)
self.__n1=n1
self.__n2=n2
def sum(self):
print("Class Variable 1:",self.__n1)
print("Class Variable 2:",self.__n2)
print("Sum:",self.__n1 + self.__n2)
S=Sample(5,10)
S.sum()
OUTPUT:
>>>
Class Variable 1: 5
Class Variable 2: 10
Sum: 15
>>>
3. Find the error in the following program to get the given output?
ERROR CODE:
class Fruits:
def __init__(self, f1, f2):
self.f1=f1
self.f2=f2
def display(self):
print("Fruit 1 = %s, Fruit 2 = %s" %(self.f1, self.f2))
F = Fruits ('Apple', 'Mango')
del F.display
F.display()
OUTPUT:
ERROR:
line 8, in <module>
del F.display
57 Visit :http://www.youtube.com/c/CSKNOWLEDGEOPENER CS KNOWLEDGE OPENER
J. BASKARAN M.Sc., B.Ed. (C.S) KNOWLEDGE OPENING & KNOWLEDGE TRANSFORMATION J. ILAKKIA M.Sc., M.Phil., B.Ed. (C.S)
AttributeError: display
CORRECT CODE:
class Fruits:
def __init__(self, f1, f2):
self.f1=f1
self.f2=f2
def display(self):
print("Fruit 1 = %s, Fruit 2 = %s" %(self.f1, self.f2))
F = Fruits ('Apple','Mango')
F.display()
OUTPUT:
obj=Greeting('Bindu Madhavan')
obj.display()
Output:
>>>
Good Morning Bindu Madhavan
>>>
5. How do define constructor and destructor in Python?
CONSTRUCTOR:
“init” is a special function begin and end with double underscore in Python act as a Constructor.
Constructor function will automatically executed when an object of a class is created.
<statements>
DESTRUCTOR:
Destructor is also a special method gets executed automatically when an object exit from the scope.
In Python, __del__( ) method is used as destructor.
General format of destructor:
def __del__(self):
<statements>
Section - D
Answer the following questions: (5 Mark)
1. Write a menu driven program to add or delete stationary items. You should use dictionary to
store items and the brand.
CODE:
stationary={}
print("\n1. Add Item \n2.Delete item \n3.Exit")
ch=int(input("\nEnter your choice: "))
while(ch==1)or(ch==2):
if(ch==1):
n=int(input("\nEnter the Number of Items to be added in the Dictionary: "))
for i in range(n):
item=input("\nEnter an Item Name: ")
brand=input("\nEnter the Brand Name: ")
stationary[item]=brand
print(stationary)
elif(ch==2):
ritem=input("\nEnter the item to be removed from the Dictionary: ")
stationary.pop(ritem)
print(stationary)
ch=int(input("\nEnter your choice: "))
59 Visit :http://www.youtube.com/c/CSKNOWLEDGEOPENER CS KNOWLEDGE OPENER
J. BASKARAN M.Sc., B.Ed. (C.S) KNOWLEDGE OPENING & KNOWLEDGE TRANSFORMATION J. ILAKKIA M.Sc., M.Phil., B.Ed. (C.S)
OUTPUT:
2. A table is known as
Section-B
Answer the following questions (2 Mark)
1. Mention few examples of a database.
Foxpro
dbase.
IBM DB2.
Microsoft Access.
Microsoft Excel.
1. Which commands provide definitions for creating table structure, deleting relations, and modifying
relation schemas.
Section-B
Answer the following questions (2 Mark)
1. Write a query that selects all students whose age is less than 18 in order wise.
This constraint ensures that no two rows This constraint declares a field as a Primary
have the same value in the specified key which helps to uniquely identify a
columns. record.
The UNIQUE constraint can be applied only The primary key does not allow NULL
to fields that have also been declared as values and therefore a primary key field must
NOT NULL. have the NOT NULL constraint.
Table constraints apply to a group of one or Column constraints apply only to individual
more columns. column.
4. Which component of SQL lets insert values in tables and which lets to create a table?
2. Write a SQL statement to modify the student table structure by adding a new field.
The SAVEPOINT command is used to temporarily save a transaction so that you can rollback to the
point whenever required.
Syntax: SAVEPOINT savepoint_name;
Example: SAVEPOINT A;
5. Write a SQL statement using DISTINCT keyword.
The DISTINCT keyword is used along with the SELECT command to eliminate duplicate rows in the
table.
This helps to eliminate redundant data.
For Example: SELECT DISTINCT Place FROM Student;
Section - D
Answer the following questions: (5 Mark)
Table Constraint
64 Visit :http://www.youtube.com/c/CSKNOWLEDGEOPENER CS KNOWLEDGE OPENER
J. BASKARAN M.Sc., B.Ed. (C.S) KNOWLEDGE OPENING & KNOWLEDGE TRANSFORMATION J. ILAKKIA M.Sc., M.Phil., B.Ed. (C.S)
(i)Unique Constraint:
This constraint ensures that no two rows have the same value in the specified columns.
For example UNIQUE constraint applied on Admno of student table ensures that no two students have
the same admission number and the constraint can be used as:
Example:
(
Admno integer NOT NULL UNIQUE, → Unique constraint
Name char (20) NOT NULL,
Gender char (1),
);
The UNIQUE constraint can be applied only to fields that have also been declared as NOT NULL.
When two constraints are applied on a single field, it is known as multiple constraints.
In the above Multiple constraints NOT NULL and UNIQUE are applied on a single field Admno.
(ii) Primary Key Constraint:
This constraint declares a field as a Primary key which helps to uniquely identify a record.
It is similar to unique constraint except that only one field of a table can be set as primary key.
The primary key does not allow NULL values and therefore a field declared as primary key must have
the NOT NULL constraint.
Example:
CREATE TABLE Student
(
Admno integer NOT NULL PRIMARY KEY, → Primary Key constraint
Name char(20)NOT NULL,
Gender char(1),
Age integer,
);
(iii) DEFAULT Constraint:
The DEFAULT constraint is used to assign a default value for the field.
When no value is given for the specified field having DEFAULT constraint, automatically the default
value will be assigned to the field.
Example:
CREATE TABLE Student
(
Admno integer NOT NULL PRIMARY KEY,
Name char(20)NOT NULL,
Gender char(1),
Age integer DEFAULT = “17”, → Default Constraint
Place char(10));
In the above example the “Age” field is assigned a default value of 17, therefore when no value is
entered in age by the user, it automatically assigns 17 to Age.
(iv) Check Constraint:
When the constraint is applied to a group of fields of the table, it is known as Table constraint.
The table constraint is normally given at the end of the table definition.
Let us take a new table namely Student1 with the following fields Admno, Firstname, Lastname,
Gender, Age, Place:
Example:
CREATE TABLE Student 1
(
Admno integer NOT NULL,
Firstname char(20),
Lastname char(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.
2. Consider the following employee table. Write SQL commands for the qtns.(i) to (v).
Components of SQL:
A Data Manipulation Language (DML) is a computer programming language used for adding
(inserting), removing (deleting), and modifying (updating) data in a database.
By Data Manipulation we mean,
Insertion of new information into the database
The Data Definition Language (DDL) consist of SQL statements used to define the database structure
or schema.
It simply deals with descriptions of the database schema and is used to create and modify the structure
of database objects in databases.
The DDL provides a set of definitions to specify the storage structure and access methods used by the
database system.
SQL commands which comes under Data Definition Language are:
Create To create tables in the database.
Truncate Remove all records from a table, also release the space occupied by those records.
A Data Control Language (DCL) is a programming language used to control the access of data stored
in a database.
It is used for controlling privileges in the database (Authorization).
The privileges are required for performing all the database operations such as creating sequences,
views of tables etc.
SQL commands which come under Data Control Language are:
Grant Grants permission to one or more users to perform specific tasks.
Transactional control language (TCL) commands are used to manage transactions in the database.
These are used to manage the changes made to the data in a table by DML statements.
5. Write a SQL statement to create a table for employee having any five fields and create a table
constraint for the employee table.
CREATE TABLE employee
(
empno integer NOT NULL,
name char(20),
desig char(20),
pay integer,
allowance integer,
PRIMARY KEY (empno)
);
(A) Flat File (B) 3D File (C) String File (D) Random File
(A) Control Return and Line Feed (B) Carriage Return and Form Feed
(C) Control Router and Line Feed (D) Carriage Return and Line Feed
3. Which of the following module is provided by Python to do several operations on the CSV files?
4. Which of the following mode is used when dealing with non-text files like image or exe files?
(A) Text mode (B) Binary mode (C) xls mode (D) csv mode
9. Making some changes in the data of the existing file or adding more data is called
Section-B
Answer the following questions (2 Mark)
1. What is CSV File?
A CSV file is a human readable text file where each line has a number of fields, separated by commas
or some other delimiter.
A CSV file is also known as a Flat File that can be imported to and exported from programs that store
data in tables, such as Microsoft Excel or OpenOfficeCalc.
2. Mention the two ways to read a CSV file using Python.
Section-C
Answer the following questions (3 Mark)
1. Write a note on open() function of python. What is the difference between the two methods?
Python has a built-in function open() to open a file.
This function returns a file object, also called a handle, as it is used to read or modify the file
accordingly.
The default is reading in text mode.
In this mode, while reading from the file the data would be in the format of strings.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-
text files like image or exe files.
2. Write a Python program to modify an existing file.
In this program, the third row of “student.csv” is modified and saved.
First the “student.csv” file is read by using csv.reader() function.
Then, the list() stores each row of the file.
The statement “lines[3] = row”, changed the third row of the file with the new content in “row”.
The file object writer using writerows (lines) writes the values of the list to “student.csv” file.
PROGRAM: student.csv
import csv
row = [„3‟, „Meena‟,‟Bangalore‟]
with open(„student.csv‟, „r‟) as readFile:
reader = csv.reader(readFile)
lines = list(reader) # list()- to store each row of data as a list
lines[3] = row
with open(„student.csv‟, „w‟) as writeFile:
# returns the writer object which converts the user data with delimiter
writer = csv.writer(writeFile)
#writerows()method writes multiple rows to a csv file
writer.writerows(lines)
readFile.close()
writeFile.close()
3. Write a Python program to read a CSV file with default delimiter comma (,).
#importing csv
import csv #opening the csv file which is in different location with read mode
with open('c:\\pyprg\\sample1.csv', 'r') as F:
#other way to open the file is f= ('c:\\pyprg\\sample1.csv', 'r')
reader = csv.reader(F) # printing each line of the Data row by row
print(row)
F.close()
OUTPUT:
['SNO', 'NAME', 'CITY']
['12101', 'RAM', 'CHENNAI']
['12102', 'LAVANYA', 'TIRUCHY']
['12103', 'LAKSHMAN', 'MADURAI']
4. What is the difference between the write mode and append mode.
Write Mode Append Mode
'w' 'a'
Open a file for writing. Open for appending at the end of the file
without truncating it.
Creates a new file if it does not exist or Creates a new file if it does not exist.
truncates the file if it exists.
Section - D
Answer the following questions: (5 Mark)
Excel is a spreadsheet that saves files into its CSV is a format for saving tabular
own proprietary format viz. xls or xlsx information into a delimited text file with
extension .csv
Excel consumes more memory while Importing CSV files can be much faster, and it
importing data also consumes less memory
Mode Description
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or truncates the
file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it. Creates a new
file if it does not exist.
't' Opren in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
3. Write the different methods to read a File in Python.
Contents of CSV file can be read with the help of csv.reader() method.
The reader function is designed to take each line of the file and make a list of all columns.
Using this method one can read data from csv files of different formats like,
The following program read a file called “sample1.csv” with default delimiter comma (,) and print row by
row.
import csv
with open('c:\\pyprg\\sample1.csv', 'r') as F:
reader = csv.reader(F)
print(row)
F.close()
OUTPUT:
['SNO', 'NAME', 'CITY']
['12101', 'RAM', 'CHENNAI']
['12102', 'LAVANYA', 'TIRUCHY']
['12103', 'LAKSHMAN', 'MADURAI']
ii) CSV files- data with Spaces at the beginning
Consider the following file “sample2.csv” containing the following data when opened through notepad
The following program read the file through Python using “csv.reader()”.
import csv
csv.register_dialect('myDialect',delimiter = ',',skipinitialspace=True)
F=open('c:\\pyprg\\sample2.csv','r')
reader = csv.reader(F, dialect='myDialect')
for row in reader:
print(row)
F.close()
OUTPUT:
['Topic1', 'Topic2', 'Topic3']
['one', 'two', 'three']
You can read the csv file with quotes, by registering new dialects using csv.register_dialect() class of
csv module.
SNO,Quotes
The following Program read “quotes.csv” file, where delimiter is comma (,) but the quotes are within
quotes (“ “).
import csv
csv.register_dialect('myDialect',delimiter = ',',quoting=csv.QUOTE_ALL,
skipinitialspace=True)
f=open('c:\\pyprg\\quotes.csv','r')
reader = csv.reader(f, dialect='myDialect')
for row in reader:
print(row)
OUTPUT:
['SNO', 'Quotes']
['1', 'The secret to getting ahead is getting started.']
['2', 'Excellence is a continuous process and not an accident.']
In the above program, register a dialect with name myDialect.
Then, we used csv. QUOTE_ALL to display all the characters after double quotes.
You can read CSV file having custom delimiter by registering a new dialect with the help of
csv.register_dialect().
In the following file called “sample4.csv”,each column is separated with | (Pipe symbol)
OUTPUT :
“SNO”,”Person”,”DOB” ”1”,”Madhu”,”18/12/2001” ”2”,”Sowmya”,”19/2/1998”
”3”,”Sangeetha”,”20/3/1999” ”4”,”Eshwar”,”21/4/2000”
“5”,”Anand”,”22/5/2001”
For example:
2. The last record in the file may or may not have an ending line break.
For example:
3.
There may be an optional header line appearing as the first line of the file with the same format as
normal record lines.
The header will contain names corresponding to the fields in the file and should contain the same
number of fields as the records in the rest of the file.
For example: field_name1,field_name2,field_name3
4.
Within the header and each record, there may be one or more fields, separated by commas.
Spaces are considered part of a field and should not be ignored.
The last field in the record must not be followed by a comma.
For example: Red , Blue
5.
6.
Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-
quotes.
For example:
7.
If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be
preceded with another double quote.
For example:
5. Which of the following is a software design technique to split your code into separate parts?
(A) Object oriented Programming (B) Modular programming
(C) Low Level Programming (D) Procedure oriented Programming
6. The module which allows you to interface with the Windows operating system is
(A) OS module (B) sys module (C) csv module (D) getopt module
7. getopt() will return an empty array if there is no error in splitting strings to
(A) argv variable (B) opt variable (C)args variable (D) ifile variable
8. Identify the function call statement in the following snippet.
if __name__ =='__main__':
main(sys.argv[1:])
(A) main(sys.argv[1:]) (B) __name__ (C) __main__ (D) argv
9. Which of the following can be used for processing text, numbers, images, and scientific data?
(A) HTML (B) C (C) C++ (D) PYTHON
10. What does __name__ contains ?
(A) c++ filename (B) main() name (C) python filename (D) os module name
Section-B
Answer the following questions (2 Mark)
1. What is the theoretical difference between Scripting language and other programming
language?
Scripting Language Programming Language
A scripting language requires an interpreter. A programming language requires a compiler.
A scripting language need not be compiled. A programming languages needs to be compiled
before running .
Example: Example:
JavaScript, VBScript, PHP, Perl, Python, Ruby, C, C++, Java, C# etc.
ASP and Tcl.
Data type is not required while declaring Data type is required while declaring
variable variable
Section - D
Answer the following questions: (5 Mark)
Example:
os.system('g++ ' + cpp_file + ' -o ' + exe_file) --
g++ compiler compiles the file cpp_file and –o (output) send to exe_file
(iii) Python getopt Module:
The getopt module of Python helps you to parse (split) command-line options and arguments.
This module provides two functions to enable command-line argument parsing.
getopt.getopt method:
This method parses command-line options and parameter list.
Syntax of getopt method:
<opts>,<args>=getopt.getopt(argv, options, [long_options])
Here is the detail of the parameters −
argv -- This is the argument list of values to be parsed (splited). In our program
the complete command will be passed as a list.
options -- This is string of option letters that the Python program recognize as, for
input or for output, with options (like „i‟ or „o‟) that followed by a colon (:).
Here colon is used to denote the mode.
long_options -- This parameter is passed with a list of strings. Argument of Long options
should be followed by an equal sign ('=').
In our program the C++ file name will be passed as string and „i‟ also will be passed along with 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 .
Opts contains list of splitted strings like mode, path and args contains any string if at all not splitted
because of wrong path or mode.
Opts contains list of splitted strings like mode, path and args contains any string if at all not splitted
because of wrong path or mode.
args will be an empty array if there is no error in splitting strings by getopt().
Example:
opts, args = getopt.getopt (argv, "i:",['ifile='])
where opts contains -- ('-i', 'c:\\pyprg\\p4')]
-i: -- option nothing but mode should be followed by :
'c:\\pyprg\\p4' -- value nothing but the absolute path of C++ file.
In our examples since the entire command line commands are parsed and no leftover argument, the
second argument args will be empty [].
If args is displayed using print() command it displays the output as [].
Example:
>>>print(args)
[]
5. Write a Python program to execute the following c++ coding.
C++ CODE:
#include <iostream>
using namespace std;
int main()
{ cout<<“WELCOME”;
return(0);
}
The above C++ program is saved in a file welcome.cpp
PYTHON PROGRAM:
import sys, os, getopt
def main(argv):
cpp_file = ''
exe_file = ''
opts, args = getopt.getopt(argv, "i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):
cpp_file = a + '.cpp'
exe_file = a + '.exe'
run(cpp_file, exe_file)
def run(cpp_file, exe_file):
print("Compiling " + cpp_file)
os.system('g++ ' + cpp_file + ' -o ' + exe_file)
print("Running " + exe_file)
print("-----------------------")
print
os.system(exe_file)
print
if __name__ =='__main__': #program starts executing from here
main(sys.argv[1:])
STEPS TO IMPORT CPP CODE INTO PYTHON CODE:
Select File→New in Notepad and type the above Python program.
Save the File as welcome.py.
Click the Run Terminal and open the command window
Go to the folder of Python using cd command.
Type the command: Python c:\pyprg\welcome.py -i c:\pyprg\welcome_cpp
OUTPUT:
------------------------------------------
WELCOME
------------------------------------------
15. DATA MANIPULATION THROUGH SQL
Section – A
Choose the best answer (1 Mark)
1. Which of the following is an organized collection of data?
(A) Database (B) DBMS (C) Information (D) Records
3. Which of the following is a control structure used to traverse and fetch the records of the
database?
4. Any changes made in the values of the record should be saved by the command
5. Which of the following executes the SQL command to perform some action?
6. Which of the following function retrieves the average of a selected column of rows in a table?
7. The function that returns the largest value of the selected column is
Section-B
Answer the following questions (2 Mark)
1. Mention the users who uses the Database.
Users of database can be human users, other programs or applications
2. Which method is used to connect a database? Give an example.
Create a connection using connect () method and pass the name of the database File.
Example:
import sqlite3
# connecting to the database
connection = sqlite3.connect ("Academy.db")
# cursor
cursor = connection.cursor()
ADVANTAGES:
SQLite is fast, rigorously tested, and flexible, making it easier to work.
Python has a native library for SQLite.
2. Mention the difference between fetchone() and fetchmany()
fetchone() fetchmany()
The fetchone() method returns the next row of The fetchmany() method returns the next
a query result set or None in case there is no row number of rows (n) of the result set.
left
Using while loop and fetchone() method we can Displaying specified number of records is done
display all the records from a table. by using fetchmany().
4. Read the following details.Based on that write a python script to display department wise
89 Visit :http://www.youtube.com/c/CSKNOWLEDGEOPENER CS KNOWLEDGE OPENER
J. BASKARAN M.Sc., B.Ed. (C.S) KNOWLEDGE OPENING & KNOWLEDGE TRANSFORMATION J. ILAKKIA M.Sc., M.Phil., B.Ed. (C.S)
records.
database name :- organization.db
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept
PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“organization.db”)
c=conn.execute(“SELECT * FROM Employee GROUP BY Dept”)
for row in c:
print(row)
conn.close()
5. Read the following details.Based on that write a python script to display records in
desending order of Eno.
database name :- organization.db
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept
PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“organization.db”)
cursor=connection.cursor()
cursor.execute(“SELECT * FROM Employee ORDER BY Eno DESC”)
result=cursor.fetchall()
print(result)
Section - D
Answer the following questions: (5 Mark)
1. Write in brief about SQLite and the steps used to use it.
SQLite is a simple relational database system, which saves its data in regular data files or even in the
internal memory of the computer.
It is designed to be embedded in applications, instead of using a separate database server program such
as MySQLor Oracle.
ADVANTAGES:
SQLite is fast, rigorously tested, and fl exible, making it easier to work.
OUTPUT:
Displaying All The Records
(1003, „Scanner‟, 10500)
(1004, „Speaker‟, 3000)
(1005, „Printer‟, 8000)
(1008, „Monitor‟, 15000)
(1010, „Mouse‟, 700)
4. Write a Python script to create a table called ITEM with following specification.
Add one record to the table.
Name of the database :- ABC
Name of the table :- Item
Column name and specification :-
Icode :- integer and act as primary key
Item Name :- Item Name :-
Rate :- Integer
Record to be added :- 1008, Monitor,15000
PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“ABC.db”)
cursor=connection.cursor()
sql_command – “““ CREATE TABLE Item(
Icode INTEGER PRIMARY KEY,
ItemName VARCHAR(25),
Rate INTEGER) ; ”””
cursor.execute(sql_command)
sql_command = “““ INSERT INTO Item(Icode, ItemName, Rate) VALUES (1008, „Monitor‟, 15000);
”””
cursor.execute(sql_command)
connection.commit()
connection.close()
print(“TABLE CREATED”)
OUTPUT:
TABLE CREATED
5. Consider the following table Supplier and item .Write a python script for (i) to (ii)
SUPPLIER
Suppno Name City Icode SuppQty
S001 Prasad Delhi 1008 100
S002 Anu Bangalore 1010 200
S003 Shahid Bangalore 1008 175
S004 Akila Hydrabad 1005 195
S005 Girish Hydrabad 1003 25
S006 Shylaja Chennai 1008 180
S007 Lavanya Mumbai 1005 325
PYTHON SCRIPT:
i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
import sqlite3
connection = sqlite3.connect(“ABC.db”)
import sqlite3
connection = sqlite3.connect(“ABC.db”)
cursor.execute(“UPDATE Supplier ST SuppQty = SuppQty +40 WHERE Name = „Akila‟ ”)
cursor.commit()
result = cursor.fetchall()
print (result)
connection.close()
OUTPUT:
3. Read the following code: Identify the purpose of this code and choose the right option from the
following.
C:\Users\YourName\AppData\Local\Programs\Python\Python36-32\Scripts>pip – version
a. Check if PIP is Installed b. Install PIP c. Download a Package d. Check PIP version
4. Read the following code: Identify the purpose of this code and choose the right option from the
5. To install matplotlib, the following function will be typed in your command prompt.
a. downloading pip to the latest version b. upgrading pip to the latest version
6. Observe the output figure. Identify the coding for obtaining this output.
Hint 1: This chart is often used to visualize a trend in data over intervas of time.
10. Read the statements given below. Identify the right option from the following for pie chart.
Statement A: To make a pie chart with Matplotlib, we can use the plt.pie() function.
Statement B: The autopct parameter allows us to display the percentage value using the Python string
formatting.
a. Statement A is correct b. Statement B is correct
c. Both the statements are correct d. Both the statements are wrong
Section-B
Answer the following questions (2 Mark)
1. Define: Data Visualization.
Data Visualization is the graphical representation of information and data.
The objective of Data Visualization is to communicate information visually to users using statistical
graphics.
2. List the general types of data visualization.
Charts
Tables
Graphs
Maps
Infographics
Dashboards
3. List the types of Visualizations in Matplotlib.
Line plot
Scatter plot
Histogram
96 Visit :http://www.youtube.com/c/CSKNOWLEDGEOPENER CS KNOWLEDGE OPENER
J. BASKARAN M.Sc., B.Ed. (C.S) KNOWLEDGE OPENING & KNOWLEDGE TRANSFORMATION J. ILAKKIA M.Sc., M.Phil., B.Ed. (C.S)
Box plot
Bar chart and
Pie chart
4. How will you install Matplotlib?
Matplotlib can be installed using pip software.
Pip is a management software for installing python packages.
Importing Matplotlib using the command: import matplotlib.pyplot as plt
Matplotlib can be imported in the workspace.
Section-C
Answer the following questions (3 Mark)
1. Draw the output for the following data visualization plot.
import matplotlib.pyplot as plt
plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Example one")
plt.bar([2,4,6,8,10],[8,6,2,5,6], label="Example two", color='g')
plt.legend()
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title('Epic Graph\nAnother Line! Whoa')
plt.show()
OUTPUT:
Program:
import matplotlib.pyplot as plt
slices=[7,2,2,13]
activities=['sleeping','eating', 'working','playing']
cols=['c','m','r','b']
plt.pie(slices, labels=activities, colors=cols,startangle=90, shadow=True,
explode=(0,0,0.1,0),autopct='%1.1f%%')
plt.title('Interesting Graph \nCheck it out')
plt.show()
Calculation for the slices:
29.2
100 x 24 = 7 [ since 24 hours a day]
8.3
100 x 24 = 1.99 =2
54.2
100 x 24 = 13 so the slices be [7,2,2,13]
Section - D
Answer the following questions: (5 Mark)
In this program,
Plt.title() → specifies title to the graph
Plt.xlabel() → specifies label for X-axis
Plt.ylabel() → specifies label for Y-axis
Output:
Bar Chart:
A BarPlot (or BarChart) is one of the most common type of plot.
It shows the relationship between a numerical variable and a categorical variable.
Bar chart represents categorical data with rectangular bars.
Each bar has a height corresponds to the value it represents.
The bars can be plotted vertically or horizontally.
It‟s useful when we want to compare a given numeric value on different categories.
To make a bar chart with Matplotlib, we can use the plt.bar() function
Example:
import matplotlib.pyplot as plt
labels = ["TAMIL", "ENGLISH", "MATHS", "PHYSICS", "CHEMISTRY", "CS"]
usage = [79.8, 67.3, 77.8, 68.4, 70.2, 88.5]
y_positions = range (len(labels))
plt.bar (y_positions, usage)
plt.xticks (y_positions, labels)
plt.ylabel ("RANGE")
plt.title ("MARKS")
plt.show()
100 Visit :http://www.youtube.com/c/CSKNOWLEDGEOPENER CS KNOWLEDGE OPENER
J. BASKARAN M.Sc., B.Ed. (C.S) KNOWLEDGE OPENING & KNOWLEDGE TRANSFORMATION J. ILAKKIA M.Sc., M.Phil., B.Ed. (C.S)
Output:
b. plt.ylabel
plt.ylabel()specifies label for Y-axis
c. plt.title
plt.title() specifies title to the graph
d. plt.legend()
Calling legend() with no arguments automatically fetches the legend handles and their associated labels.
e. plt.show()
Display a figure. When running in Python with its Pylab mode,display all figures and return to the
Python prompt.
PREPARED BY