0% found this document useful (0 votes)
52 views48 pages

12CS em 2

The document discusses strings and string manipulation in Python. It covers string operators, slicing, indexing, formatting characters and other string methods. It also covers lists, tuples, sets and dictionaries including their properties and common functions.
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)
52 views48 pages

12CS em 2

The document discusses strings and string manipulation in Python. It covers string operators, slicing, indexing, formatting characters and other string methods. It also covers lists, tuples, sets and dictionaries including their properties and common functions.
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/ 48

8 STRINGS AND STRING MANIPULATION

I. Choose the best answer: (1 Mark)


1. Which of the following is the output of the following python code?
str1="TamilNadu"
print(str1[::-1])
(A) Tamilnadu (B) Tmlau (C) udanlimaT (D) udaNlimaT
2. What will be the output of the following code?
str1 = "Chennai Schools"
str1[7] = "-"
(A) Chennai-Schools (B) Chenna-School
(C) Type error (D) Chennai
3. Which of the following operator is used for concatenation?
(A) + (B) & (C) * (D) =
4. Defining strings within triple quotes allows creating:
(A) Single line Strings (B) Multiline Strings
(C) Double line Strings (D) Multiple Strings
5. Strings in python:
(A) Changeable (B) Mutable (C) Immutable (D) flexible
6. Which of the following is the slicing operator?
(A) { } (B) [ ] (C) < > (D) ( )
7. What is stride?
(A) index value of slide operation (B) first argument of slice operation
(C) second argument of slice operation (D) third argument of slice operation
8. Which of the following formatting character is used to print exponential notation in
upper case?
(A) %e (B) %E (C) %g (D) %n
9. Which of the following is used as placeholders or replacement fields which get
replaced along with format( ) function?
(A) { } (B) < > (C) ++ (D) ^^
10. The subscript of a string may be:
(A) Positive (B) Negative
(C) Both (A) and (B) (D) Either (A) or (B)

..47..
12 – Computer Science

II. Answer the following questions: (2 Marks)


1. What is String?
String is a sequence of Unicode characters that may be a combination of letters,
numbers, or special symbols enclosed within single, double or even triple quotes.
Example:
‘School’
“School”
‘‘‘School’’’
2. Do you modify a string in Python?
No. Strings are immutable in python.
3. How will you delete a string in Python?
Python will not allow deleting a string. Whereas you can remove entire string
variable using del command.
Example:
>>> str1="Hello"
>>> del str1
4. What will be the output of the following python code?
str1 = “School”
print(str1*3)
Output:
SchoolSchoolSchool
5. What is slicing?
Slice is a substring of a main string. A substring can be taken from the original
string by using [ ] operator and index or subscript values.
III. Answer the following questions: (3 Marks)
1. Write a Python program to display the given pattern
COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C
..48..
12 – Computer Science

Program:
str="COMPUTER"
i = len(str)
while (i > 0):
print(str[:i])
i = i -1
2. Write a short about the followings with suitable example:
(a) capitalize( ) (b) swapcase( )
(a) capitalize( ):
It used to capitalize the first character of the string.
Example:
>>> city="chennai"
>>> print(city.capitalize())
Chennai
(b) swapcase( )
It will change case of every character to its opposite case vice-versa.
Example:
>>>str1="tamil NADU"
>>> print(str1.swapcase())
TAMIL nadu
3. What will be the output of the given python program?
str1 = "welcome"
str2 = "to school"
str3=str1[:2]+str2[len(str2)-2:]
print(str3)
Output:
weol
4. What is the use of format()? Give an example.
The format() function used with strings is very versatile and powerful function
used for formatting strings. The curly braces {} are used as placeholders or
replacement fields which get replaced along with format() function.
Example:
a=2
..49..
12 – Computer Science

b=4
print(“The product of {} and {} is {}”, format(a, b, ab))
Output:
The product of 2 and 4 is 8
5. Write a note about count() function in python.
count() function returns the number of substrings occurs within the given range.
Remember that substring may be a single character.
Syntax:
count(str[,beg, end])
Example
>>>str1="Raja Raja Chozhan"
>>>print(str1.count('Raja'))
2
>>>print(str1.count('a'))
5
IV. Answer the following questions: (5 Marks)
1. Explain about string operators in python with suitable example.
String Operators
Python provides the following operators for string operations. These operators are
useful to manipulate string.
(i) Concatenation (+)
Joining of two or more strings is called as Concatenation. The plus (+) operator
is used to concatenate strings in python.
Example
>>> "welcome to " + "Python"
welcome to Python'
(ii) Append (+=)
Adding more strings at the end of an existing string is known as append. The
operator += is used to append a new string with an existing string.
Example
>>> str1="Welcome to "
>>> str1+="Learn Python"
>>> print (str1)
Welcome to Learn Python

..50..
12 – Computer Science

(iii) Repeating ()


The multiplication operator () is used to display a string in multiple number
of times.
Example
>>> str1="Welcome "
>>> print (str14)
Welcome Welcome Welcome Welcome
(iv) String slicing
Slice is a substring of a main string. A substring can be taken from the original
string by using [] operator and index or subscript values.
Syntax:
str[start:end]
Where start is the beginning index and end is the last index value of a
character in the string. Python takes the end value less than one from the
actual index specified.
Example:
>>> str1="THIRUKKURAL"
>>> print (str1[0])
T
>>> print (str1[0:5])
THIRU
(v) Stride when slicing string
When the slicing operation, you can specify a third argument as the stride,
which refers to the number of characters to move forward after the first character
is retrieved from the string. The default value of stride is 1.
Example:
>>> str1 = "Welcome to learn Python"
>>> print (str1[10:16])
learn
>>> print (str1[10:16:4])
r
>>> print (str1[10:16:2])
er

..51..
9 LISTS, TUPLES, SETS AND DICTIONARY

I. Choose the best answer: (1 Mark)


1. Pick odd one in connection with collection data type
(A) List (B) Tuple (C) Dictionary (D) Loop
2. Let list1=[2,4,6,8,10], then print(List1[-2]) will result in
(A) 10 (B) 8 (C) 4 (D) 6
3. Which of the following function is used to count the number of elements in a list?
(A) count() (B) find() (C) len() (D) index()
4. If List=[10,20,30,40,50] then List[2]=35 will result
(A) [35,10,20,30,40,50] (B) [10,20,30,40,50,35]
(C) [10,20,35,40,50] (D) [10,35,30,40,50]
5. If List=[17,23,41,10] then List.append(32) will result
(A) [32,17,23,41,10] (B) [17,23,41,10,32]
(C) [10,17,23,32,41] (D) [41,32,23,17,10]
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?
S=[x**2 for x in range(5)]
print(S)
(A) [0,1,2,4,5] (B) [0,1,4,9,16]
(C) [0,1,4,9,16,25] (D) [1,4,9,16,25]
8. What is the use of type() function in python?
(A) To create a Tuple
(B) To know the type of an element in tuple.
(C) To know the data type of python object.
(D) To create a list.
9. Which of the following statement is not correct?
(A) A list is mutable
(B) A tuple is immutable.
(C) The append() function is used to add an element.
(D) The extend() function is used in tuple to add elements in a list.

..52..
12 – Computer Science

10. Let setA={3,6,9}, setB={1,3,9}. What will be the result of the following snippet?
print(setA|setB)
(A) {3,6,9,1,3,9} (B) {3,9} (C) {1} (D) {1,3,6,9}
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?
(A) Symmetric difference (B) Difference
(C) Intersection (D) Union
12. The keys in Python, dictionary is specified by
(A) = (B) ; (C)+ (D) :
II. Answer the following questions: (2 Marks)
1. What is List in Python?
A list in Python is known as a “sequence data type” like strings. It is an ordered
collection of values enclosed within square brackets []. Each value of a list is called as
element.
2. How will you access the list elements in reverse order?
In Python, we can access the list elements in reverse order using reverse indexing.
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.
Example:
Marks = [10, 23, 41, 75]
i = -1
while i >= -4:
print (Marks[i])
i = i -1
Output
75
41
23
10
3. What will be the value of x in following python code?
List1=[2,4,6,[1,3,5]]
x=len(List1)
The value of x is 4

..53..
12 – Computer Science

4. Differentiate del with remove() function of List.


➢ del statement is used to delete known elements.
➢ remove() function is used to delete elements of a list if its index is unknown.
Example:
marks = [50, 63, 41, 75]
del marks[1] or marks.remove(63)
5. Write the syntax of creating a Tuple with n number of elements.
Syntax:
Tuple_Name = (E1, E2, E2 ……. En)
(Or)
Tuple_Name = E1, E2, E3 ….. En
6. What is set in Python?
A Set is a mutable and an unordered collection of elements without duplicates.
That means the elements within a set cannot be repeated.
III. Answer the following questions: (3 Marks)
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 parenthesis.
❖ Iterating tuples is faster than list.
2. Write a short note about sort( ).
sort() function arranges a list value in ascending order by default.
Syntax:
list.sort([reverse=True|False, key=myFunc])
✓ Both arguments are optional.
✓ If reverse is set as True, list sorting is in descending order.
Example:
MyList=[5,2,3,4,1]
MyList.sort( )
print(MyList)
MyList.sort(reverse=True)
print(MyList)
..54..
12 – Computer Science

Output:
[1,2,3,4,5]
[5,4,3,2,1]
3. What will be the output of the following code?
list = [2x for x in range(5)]
print(list)
Output:
[1, 2, 4, 8, 16]
4. Explain the difference between del and clear() in dictionary with an example.
➢ In Python dictionary, del keyword is used to delete a particular element.
➢ The clear() function is used to delete all the elements in a dictionary.
➢ To remove the dictionary, you can use del keyword with dictionary name.
Example:
Dict = {'Mark1' : 98, 'Marl2' : 86}
del Dict['Mark1']
print(Dict)
Dict.clear()
print(Dict)
del Dict
print(Dict)
Output:
{'Mark2': 86}
{}
NameError: name 'Dict' is not defined
5. List out the set operations supported by python.
Python supports the set operations such as
(i) Union (I) :
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 fi rst set (say set A) but not in the second set
(say set B)
..55..
12 – Computer Science

(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.
6. What are the difference between List and Dictionary?
List Dictionary
List is an ordered set of elements. Dictionary is a data structure that is used
for matching one element (Key) with
another (Value).
The index values can be used to access a In dictionary key represents index.
particular element.
Lists are used to look up a value. It is used to take one value and look up
another value.
IV. Answer the following questions: (5 Marks)
1. What the different ways to insert an element in a list. Explain with suitable example.
There are three methods are used to insert the elements in a list.
(i) append():
In Python, append( ) function is used to add a single element to an existing list.
Syntax:
List.append(element to be added)
Example:
>>>Marks = [10, 23, 41, 75]
>>>Marks.append(60)
>>>print(Marks)
[10, 23, 41, 75, 60]
(ii) extend():
In python, extend( ) function is used to add more than one element to an existing
list.
Syntax:
List.extend([elements to be added])
Example:
>>>Marks = [10, 23, 41, 75]
>>>Marks.extend([60,80,55])
>>>print(Marks)
[10, 23, 41, 75, 60,80,55]

..56..
12 – Computer Science

(iii) insert():
The insert( ) function is used to insert an element at any position of a list.
Syntax:
List.insert (position index, element)
Example:
>>>Marks = [10, 23, 41, 75]
>>>Marks.insert(2,60)
>>>print(Marks)
[10, 23, 60, 41, 75]
While inserting a new element in between the existing elements, at a particular
location, the existing elements shifts one position to the right.
2. What is the purpose of range( )? Explain with an example.
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.
Syntax:
range (start value, end value, step value)
where,
✓ start value – beginning value of series
✓ end value – final value of series.
✓ step value – It is an optional argument, which refers to increment
value.
Example:
for x in range (2, 11, 2):
print(x, end=’ ’)
Output:
2 4 6 8 10
Creating a list with range() function:
➢ Using the range( ) function, you can create a list with series of values.
➢ The list( ) function makes the result of range( ) as a list.
Syntax:
List_Varibale = list (range())
Example:
>>> Even_List = list(range(2,11,2))
..57..
12 – Computer Science

>>> print(Even_List)
[2, 4, 6, 8, 10]
In the above code, list( ) function takes the result of range( ) as Even_List elements.
3. What is nested tuple? Explain with an example.
➢ 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:
voters=(("Aruna", "F", 36), ('Ram", "F", 47), ("Suriya", "M", 35), ("Kamal", "M", 23))
for i in voters:
print(i)
Output:
(‘Aruna’, ‘F’, 36)
(‘Rani’, ‘F', 47)
('Suriya', ‘M', 35)
(‘Kamal’, 'M', 23)
4. Explain the different set operations supported by python with suitable example.
Python supports the set operations such as Union, Intersection, Difference and
Symmetric difference.
(i) Union:
➢ It includes all elements from two or more sets.
➢ In python, the operator | and the function union( ) are used to join two sets
in python.
Example:
set_A = {2,4,6,8}
set_B = {'A', 'B', 'C', 'D'}
print(set_A|set_B) (OR) print(set_A.union(set_B)
Output:
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}
(ii) Intersection:
➢ It includes the common elements in two sets.
➢ The operator & and the function intersection( ) are used to intersect two sets
in python.

..58..
12 – Computer Science

Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B) (OR) print(set_A.intersection(set_B))
Output:
{'A', 'D'}
(iii) Difference:
➢ It includes all elements that are in first set but not in the second set.
➢ The minus (-) operator and the function difference( ) are used to difference
operation.
Example:
set_A={'A', 2, 4, 'D'} .
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B) (OR) print(set_A.diff erence(set_B))
Output:
{2, 4}
(iv) Symmetric difference:
➢ It includes all the elements that are in two sets but not the one that are
common to two sets.
➢ The caret (^) operator and the function symmetric_difference() are used to
symmetric difference set operation in python.
Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B) (OR) print(set_A.symmetric_difference(set_B))
Output:
{2, 4, 'B', 'C'}

..59..
10 PYTHON CLASSES AND OBJECTS

I. Choose the best answer: (1 Mark)


1. Which of the following are the key features of an Object-Oriented Programming
language?
(A) Constructor and Classes (B) Constructor and Object
(C) Classes and Objects (D) Constructor and Destructor
2. Functions defined inside a class:
(A) Functions (B) Module (C) Methods (D) section
3. Class members are accessed through which operator?
(A) & (B) . (C) # (D) %
4. Which of the following method is automatically executed when an object is created?
(A) __object__( ) (B) __del__( ) (C) __func__( ) (D) __init__( )
5. A private class variable is prefixed with
(A) __ (B) && (C) ## (D) **
6. Which of the following method is used as destructor?
(A) __init__( ) (B) __dest__( ) (C) __rem__( ) (D) __del__( )
7. Which of the following class declaration is correct?
(A) class class_name (B) class class_name<>
(C) class class_name: (D) class class_name[ ]
8. Which of the following is the output of the following program?
class Student:
def __init__(self, name):
self.name=name
print (self.name)
S=Student(“Tamil”)
(A) Error (B) Tamil (C) name (D) self
9. Which of the following is the private class variable?
(A) __num (B) ##num (C) $$num (D) &&num
10. The process of creating an object is called as:
(A) Constructor (B) Destructor
(C) Initialize (D) Instantiation

..60..
12 – Computer Science

II. Answer the following questions: (2 Marks)


1. What is class?
class is a template for the object. It is the main building block in Python.
2. What is instantiation?
The process of creating object is called as “Class Instantiation”.
3. What is the output of the following program?
class Sample:
__num=10
def disp(self):
print(self.__num)
S=Sample()
S.disp()
print(S.__num)
Output:
10
Attribute Error: 'Sample' object has no attribute '__num'
4. How will you create constructor in Python?
➢ In Python, Constructor is the special function called “init” that is automatically
executed when an object of a class is created.
➢ It must begin and end with double underscore.
Syntax:
def __init__(self, [args ……..]):
<statements>
Example:
class Sample:
def __init__(self):
print("Constructor of class Sample...")
S=Sample()
Output:
Constructor of class Sample...
5. What is the purpose of Destructor?
➢ Destructor is also a special method gets executed automatically when an object
exit from the scope.
..61..
12 – Computer Science

➢ It is just opposite to constructor.


➢ In Python, __del__( ) method is used as destructor.
III. Answer the following questions: (3 Marks)
1. What are class members? How do you define it?
➢ Variables and functions defined inside a class are called as “Class Variable” and
“Methods” respectively.
➢ Class variable and methods are together known as members of the class.
Example:
class Sample:
x = 10 → class variable
def disp(self): → method
print(Sample.x)
s = Sample()
s.disp()
In the above code, name of the class is Sample and it has a variables x and method
disp(self) respectively. We can access the class members using the object s.
2. Write a class with two private class variables and print the sum using a method.
Program:
class sample:
def __init__(self,n1,n2):
self.__n1=n1
self.__n2=n2
def sum(self):
print(self.__n1 + self.__n2)
s=sample(12,14)
s.sum()
Output:
26
3. Find the error in the following program to get the given output?
class Fruits:
def __init__(self, f1, f2):
self.f1=f1
self.f2=f2
..62..
12 – Computer Science

def display(self):
print("Fruit 1 = %s, Fruit 2 = %s" %(self.f1, self.f2))
F = Fruits ('Apple', 'Mango')
del F.display
F.display()
Output:
Fruit 1 = Apple, Fruit 2 = Mango
✓ The statement “del F.display” should be removed to get the given output.
4. What is the output of the following program?
class Greeting:
def __init__(self, name):
self.__name = name
def display(self):
print("Good Morning ", self.__name)
obj=Greeting('Bindu Madhavan')
obj.display()
Output:
Good Morning Bindu Madhavan
5. How do define constructor and destructor in Python?
Syntax of Constructor:
def __init__(self, [args ……..]):
<statements>
Syntax of Destructor:
def __del__(self):
<statements>
Example:
class sample:
def __init__(self,n1):
self.__n1=n1
print("Constructor of class Sample...")
def __del__(self):
print("Destructor of class Sample...")
s=sample(5)
..63..
12 – Computer Science

Output:
Constructor of class Sample...
Destructor of class Sample...
IV. Answer the following questions: (5 Marks)
1. Write a menu driven program to add or delete stationary items. You should use
dictionary to store items and the brand.
Program:
stat = { }
print("1.Add, 2.Delete, 3.Display, 4.Exit")
ch=int(input("Enter your choice (1/2/3/4) : "))
while(ch!=4):
if ch==1:
nme=input("Enter stationary name : ")
brand=input("Enter brand name : ")
stat[nme]=brand
pass
elif ch==2:
nme=input("Enter stationary name to delete:")
del stat[nme]
elif ch==3:
print(stat)
else:
break
ch=int(input("Enter your choice (1/2/3/4) : "))

The following output is only for your reference. No need to write it in the
examination.
Output:
1.Add, 2.Delete, 3.Display, 4.Exit
Enter your choice (1/2/3/4) : 1
Enter stationary name : Pen
Enter brand name : Camel

..64..
12 – Computer Science

Enter your choice (1/2/3/4) : 1


Enter stationary name : Pencil
Enter brand name : HP
Enter your choice (1/2/3/4) : 1
Enter stationary name : Eraser
Enter brand name : Natraj
Enter your choice (1/2/3/4) : 3
{'Pen': ‘Camel’, ‘Pencil’: 'HP’, ‘Eraser’: ‘Natraj’}
Enter your choice (1/2/3/4) : 2
Enter stationary name to delete : Pencil
Enter your choice (1/2/3/4) : 3
{ Pen’: ‘Camel’, ‘Eraser’: ‘Natraj’}
Enter your choice (1/2/3/4) : 4

..65..
11 DATABASE CONCEPTS

I. Choose the best answer: (1 Mark)


1. What is the acronym of DBMS?
(A) DataBase Management Symbol (B) Database Managing System
(C) DataBase Management System (D) DataBasic Management System
2. A table is known as
(A) tuple (B) attribute (C) relation (D) entity
3. Which database model represents parent-child relationship?
(A) Relational (B) Network (C) Hierarchical (D) Object
4. Relational database model was first proposed by
(A) E F Codd (B) E E Codd (C) E F Cadd (D) E F Codder
5. What type of relationship does hierarchical model represents?
(A) one-to-one (B) one-to-many
(C) many-to-one (D) many-to-many
6. Who is called Father of Relational Database from the following?
(A) Chris Date (B) Hugh Darween
(C) Edgar Frank Codd (D) Edgar Frank Cadd
7. Which of the following is an RDBMS?
(A) Dbase (B) Foxpro (C) Microsoft Access (D) SQLite
8. What symbol is used for SELECT statement?
(A) σ (B) Π (C) X (D) Ω
9. A tuple is also known as
(A) table (B) row (C) attribute (D) field
10. Who developed ER model?
(A) Chen (B) EF Codd (C) Chend (D) Chand
II. Answer the following questions: (2 Marks)
1. Mention few examples of a database.
➢ Microsoft Access
➢ dBase
➢ FoxPro
➢ Oracle
➢ MySQL

..66..
12 – Computer Science

2. List some examples of RDBMS.


➢ SQL Server
➢ Oracle
➢ MySQL
➢ SQLite
➢ MariaDB
3. What is data consistency?
Data Consistency means that data values are the same at all instances of a database .
4. What is the difference between Hierarchical and Network data model?
❖ In hierarchical model, a child record has only one parent node.
❖ In a Network model, a child may have many parent nodes. It represents the data
in many-to-many relationships.
❖ This model is easier and faster to access the data.
5. What is normalization?
Database normalization was first proposed by Dr. Edgar F Codd as an integral part
of RDBMS in order to reduce data redundancy and improve data integrity. These rules
are known as E F Codd Rules.
III. Answer the following questions: (3 Marks)
1. What is the difference between Select and Project command?
Select Project
The SELECT operation is used for The projection eliminates all attributes
selecting a subset with tuples according of the input relation but those
to a given condition. mentioned in the projection list.
Select filters out all tuples that do not satisfy The projection method defines a
the condition. relation that contains a vertical subset of
Relation.
symbol : σ symbol : ∏
2. What is the role of DBA?
Database Administrator or DBA is the one who manages the complete database
management system. DBA takes care of the security of the DBMS, managing the
license keys, managing user accounts and access etc.

..67..
12 – Computer Science

3. Explain Cartesian product with a suitable example.


❖ Cross product is a way of combining two relations. The resulting relation contains,
both relations being combined.
❖ A x B means A times B, where the relation A and B have different attributes.
Table A Table B
RollNo Name SubCode Subject
1051 Aakash 041 Maths
1052 Subitha 019 Computer Science
Cartesian product : Table A x Table B
RollNo Name SubCode Subject
1051 Aakash 041 Maths
1051 Aakash 019 Computer Science
1052 Subitha 041 Maths
1052 Subitha 019 Computer Science
4. Explain Object Model with example.
❖ Object model stores the data in the form of objects, attributes and methods,
classes and Inheritance.
❖ This model handles more complex applications, such as Geographic information
System (GIS), scientific experiments, engineering design and manufacturing.
❖ It is used in file Management System.
❖ It represents real world objects, attributes and behaviours.
Example:
Shape
get_area()
get_perimeter()

Rectangle Triangle
Circle
length base
radius
breadth height
where,
✓ Shape is the class.
✓ Circle, Rectangle and Triangle are objects of class Shape.
✓ radius, length, breadth, base and height are attributes.
✓ get_area() and get_perimeter() are the methods.

..68..
12 – Computer Science

5. Write a note on different types of DBMS users.


➢ Database Administrators:
Database Administrator or DBA is the one who manages the complete
database management system. DBA takes care of the security of the DBMS,
managing the license keys, managing user accounts and access etc.
➢ Application Programmers or Software Developers:
This user group is involved in developing and designing the parts of DBMS.
➢ End User:
End users are the one who store, retrieve, update and delete data.
➢ Database designers:
Are responsible for identifying the data to be stored in the database for
choosing appropriate structures to represent and store the data.
IV. Answer the following questions: (5 Marks)
1. Explain the different types of data model.
1. Hierarchical Model:
➢ Hierarchical model was developed by IBM.
➢ In Hierarchical model, data is represented as a simple tree like structure form.
This model represents a one-to-many relationshipi.e., parent-child relationship.
➢ One child can have only one parent but one parent can have many children.
➢ This model is mainly used in IBM Main Frame computers.

School

Course Resources

Theory Lab

2. Relational Model:
➢ The Relational Database model was first proposed by E.F. Codd in 1970.
➢ Nowadays, it is the most widespread data model used for database applications
around the world.
➢ The basic structure of data in relational model is tables (relations).
➢ All the information’s related to a particular type is stored in rows of that table.
..69..
12 – Computer Science

➢ A relation key is an attribute which uniquely identifies a particular tuple.

Stu_id Name Age Sub_id Subject Teacher


1 Aruna 17 1 Tamil Jegan
2 Prabhakar 16 2 Maths Veni
3 Aakash 15 3 Science Jeya

Stu_id Sub_id Marks


1 1 98
2 2 87
3 2 75
3. Network Model:
➢ Network database model is an extended form of hierarchical data model.
➢ The difference between hierarchical and Network data model is:
❖ In hierarchical model, a child record has only one parent node.
❖ In a Network model, a child may have many parent nodes. It represents
the data in many-to-many relationships.
❖ This model is easier and faster to access the data.

School Parent Node

Library Office Staff Room Child to School (Parent Node)

Student has 3 Parents


Student
(one to many relationship)

4. Entity Relationship Model (ER model):


➢ In this database model, relationships are created by dividing the object into
entity and its characteristics into attributes.
➢ It was developed by Chen in 1976.
➢ This model is useful in developing a conceptual design for the database.
➢ It is very simple and easy to design logical view of data.
..70..
12 – Computer Science

➢ The different shapes used in ER diagram is


✓ Rectangle represents the entities.
Example: Doctor and Patient
✓ Ellipse represents the attributes.
Example: D-id, D-Name, P-id and P-Name
✓ Diamond represents the relationships.
Example: Doctor diagnosis the Patient

Doctor Patient
Diagnosis

D-id D-Name P-id P-Name

5. Object Model:
➢ Object model stores the data in the form of objects, attributes and methods,
classes and Inheritance.
➢ This model handles more complex applications, such as Geographic
information System (GIS), scientific experiments, engineering design and
manufacturing.
➢ It is used in file Management System.
➢ It represents real world objects, attributes and behaviours.
Example:

Shape
get_area()
get_perimeter(
)

Circle Rectangle Triangle


radius length base
breadth height
where,
✓ Shape is the class.
✓ Circle, Rectangle and Triangle are objects of class Shape.
✓ radius, length, breadth, base and height are attributes.
✓ get_area() and get_perimeter() are the methods.
..71..
12 – Computer Science

2. Explain the different types of relationship mapping.


1. One-to-One Relationship: Student Exam No
➢ In One-to-One Relationship, one
entity is related with only one
other entity. Rifayah 1001
➢ One row in a table is linked with
only one row in another table Vignesh 1002
and vice versa.
For example: Anand 1003
A student can have only one
exam number.
2. One-to-Many Relationship: Staff
➢ In One-to-Many relationship, Department
one entity is related to many
Jeya
other entities.
➢ One row in a table A is linked to Tamil Aruna
many rows in a table B, but one
row in a table B is linked to only Maths Prabhu
one row in table A.
For example: Computer Anand
One Department has many staff
members. Raja

3. Many-to-One Relationship:
➢ In Many-to-One Relationship, Staff Department
many entities can be related with
only one in the other entity.
➢ Multiple rows in staff members Rifayah Maths
table is related with only one row
in Department table. Vignesh Computer
For example:
Anand
A number of staff members
working in one Department.

..72..
12 – Computer Science

4. Many-to-Many Relationship: Book Student


➢ A many-to-many relationship
occurs when multiple records
in a table are associated with Python Sumith
multiple records in another a
SQL Jino
table.
For example:
C++ Anbu
Many Books in a Library are
issued to many students.

3. Differentiate DBMS and RDBMS.


Basis of Comparison DBMS RDBMS

Expansion Database Management Relational DataBase


System Management System

Data storage Navigational model ie data Relational model (in tables).


by linked records ie data in tables as row and
column
Data redundancy Exhibit Not Present

Normalization Not performed RDBMS uses normalization


to reduce redundancy

Data access Consumes more time Faster, compared to DBMS.


Keys and indexes Does not use. used to establish
relationship. Keys are used
in RDBMS.

Transaction management Inefficient, Efficient and secure.


Error prone and insecure.
Distributed Databases Not supported Supported by RDBMS.

Example Dbase, FoxPro SQL server, Oracle, mysql,


MariaDB, SQLite.

..73..
12 – Computer Science

4. Explain the different operators in Relational algebra with suitable examples.


I. Unary Relational Operations:
SELECT (symbol : σ)
➢ General form σc ( R ) with a relation R and a condition C on the attributes of R.
➢ The SELECT operation is used for selecting a subset with tuples according to a
given condition. Select
➢ filters out all tuples that do not satisfy C.
STUDENT
Studno Name Course Year
cs1 Kannan Big Data II
cs2 Gowri Shankar R language I
cs3 Lenin Big Data I
cs4 Padmaja Python I
Programming

σcourse = “Big Data” (STUDENT )

Studno Name Course Year


cs1 Kannan Big Data II
cs3 Lenin Big Data I
PROJECT (symbol : Π)
➢ The projection eliminates all attributes of the input relation but those mentioned
in the projection list.
➢ The projection method defines a relation that contains a vertical subset of
Relation.
Example:
Πcourse (STUDENT)
Result

Course
Big Data
R language
Python Programming

..74..
12 – Computer Science

II. Relational Algebra Operations from Set Theory:


For example, consider the following tables

Table A Table B

Studno Name Studno Name

cs1 Kannan cs1 Kannan

cs3 Lenin cs2 GowriShankarn

cs4 Padmaja cs3 Lenin

UNION (Symbol :∪)


➢ It includes all tuples that are in tables A or in B. It also eliminates duplicates.
➢ Set A Union Set B would be expressed as A ∪ B
Result
Table A ∪ B
Studno Name
cs1 Kannan
cs2 GowriShankar
cs3 Lenin
cs4 Padmaja

SET DIFFERENCE (Symbol : -)


➢ The result of A – B, is a relation which includes all tuples that are in A but not in B.
➢ The attribute name of A has to match with the attribute name in B and the result
is,

Table A - B
Studno Name
cs4 Padmaja

..75..
12 – Computer Science

INTERSECTION (symbol: ∩) A ∩ B
➢ Defines a relation consisting of a set of all tuple that are in both in A and B.
However, A and B must be union-compatible.

A∩B
Studno Name
cs1 Kannan
cs3 Lenin

PRODUCT OR CARTESIAN PRODUCT (Symbol: X)


➢ Cross product is a way of combining two relations. The resulting relation contains,
both relations being combined.
➢ A x B means A times B, where the relation A and B have different attributes.
Table A Table B
RollNo Name SubCode Subject
1051 Aakash 041 Maths
1052 Subitha 019 Computer Science

Cartesian product : Table A x Table B


RollNo Name SubCode Subject
1051 Aakash 041 Maths
1051 Aakash 019 Computer Science
1052 Subitha 041 Maths
1052 Subitha 019 Computer Science
5. Explain the characteristics of DBMS.
1. Data stored into Data is stored into tables, created inside the database.
Tables DBMS also allows to have relationship between tables
which makes the data more meaningful and connected.
2. Reduced DBMS follows Normalisation which divides the data in
Redundancy such a way that repetition is minimum.

..76..
12 – Computer Science

3. Data Consistency On live data, it is being continuously updated and added,


maintaining the consistency of data can become a
challenge. But DBMS handles it by itself.
4. Support Multiple DBMS allows multiple users to work on it (update, insert,
user and Concurrent delete data) at the same time and still manages to
Access maintain the data consistency.
5. Query Language DBMS provides users with a simple query language, using
which data can be easily fetched, inserted, deleted and
updated in a database.
6. Security The DBMS also takes care of the security of data,
protecting the data from unauthorized access.
7. DBMS Supports Transactions It allows us to better handle and manage
data integrity in real world applications where multi-
threading is extensively used.

..77..
12 STRUCTURED QUERY LANGUAGE (SQL)

I. Choose the best answer: (1 Mark)


1. Which commands provide definitions for creating table structure, deleting relations,
and modifying relation schemas.
(A) DDL (B) DML (C) DCL (D) DQL
2. Which command lets to change the structure of the table?
(A) SELECT (B) ORDER BY (C) MODIFY (D) ALTER
3. The command to delete a table is
(A) DROP (B) DELETE (C) DELETE ALL (D) ALTER TABLE
4. Queries can be generated using
(A) SELECT (B) ORDER BY (C) MODIFY (D) ALTER
5. The clause used to sort data in a database
(A) SORT BY (B) ORDER BY (C) GROUP BY (D) SELECT
II. Answer the following questions: (2 Marks)
1. Write a query that selects all students whose age is less than 18 in order wise.
Select name from student where age<18 order by age;
2. Differentiate Unique and Primary Key constraint.
Unique Constraint Primary Key Constraint
It ensures that no two rows have the It declares a field as a Primary key which
same value in the specified columns. helps to uniquely identify a record.
More than one fields of a table can be Only one field of a table can be set as
set as primary key. primary key.
3. Write the difference between table constraint and column constraint?
➢ Table constraint: Table constraint apply to a group of one or more columns.
➢ Column constraint: Column constraint apply only to individual column.
4. Which component of SQL lets insert values in tables and which lets to create a table?
➢ DDL (Data Definition Language) – to create tables
➢ DML (Data Manipulation Language) – to insert values
5. What is the difference between SQL and MySQL?
❖ SQL : Structured Query Language is a language used for accessing database.
❖ MySQL : MySQL is a Database Management System like SQL Server, Oracle. MySQL
is a RDBMS.

..78..
12 – Computer Science

III. Answer the following questions: (3 Marks)


1. What is a constraint? Write short note on Primary key constraint.
➢ Constraint is a condition applicable on a field or set of fields.
➢ Primary Key Constraint:
This constraint declares a field as a Primary key which helps to uniquely identify
a record. The primary key does not allow NULL values and therefore a field
declared as primary key must have the NOT NULL constraint.
2. Write a SQL statement to modify the student table structure by adding a new field.
ALTER TABLE student add address char(20);
3. Write any three DDL commands.
➢ Create: To create tables in the database.
➢ Alter: Alters the structure of the database.
➢ Drop: Delete tables from database.
➢ Truncate: Remove all records from a table, also release the space occupied by
those records.
4. Write the use of Savepoint command with an example.
➢ The SAVEPOINT command is used to temporarily save a transaction so that you
can rollback to the point whenever required.
➢ The different states of our table can be saved at anytime using different names
and the rollback to that state can be done using the ROLLBACK command.
Syntax:
SAVEPOINT savepoint_name;
Example:

Admno Name Age


105 Sumitha 21
106 Selvam 48
107 Aakash 14
UPDATE Student SET Name = ‘Mini’ WHERE Admno=105;
SAVEPOINT A;

..79..
12 – Computer Science

SELECT * FROM STUDENT;

Admno Name Age


105 Mini 21
106 Selvam 48
107 Aakash 14
ROLLBACK TO A;
SELECT * FROM STUDENT;

Admno Name Age


105 Sumitha 21
106 Selvam 48
107 Aakash 14
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:

Admno Name Age Place


105 Sumitha 21 Madurai
106 Selvam 48 Chennai
107 Aakash 14 Chennai
108 Aruna 36 Coimbatore
109 Madhan 19 Madurai

SELECT DISTINCT Place FROM Student;


will display the following data:

Place
Madurai
Chennai
Coimbatore

..80..
12 – Computer Science

IV. Answer the following questions: (5 Marks)


1. Write the different types of constraints and their functions.
Constraints ensure database integrity, therefore known as database integrity
constraints. The different types of constraints are as follows
(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:
CREATE TABLE Student
(
Admno integer NOT NULL UNIQUE, → Unique constraint
Name char (20) NOT NULL
);
(ii) Primary Key Constraint:
➢ It is similar to unique constraint except that only one field of a table can be set
as primary key which helps to uniquely identify a record.
➢ 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
);
(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.
(iv) CHECK Constraint:
➢ This constraint helps to set a limit value placed for a field. When we define a
check constraint on a single column, it allows only the restricted values on that
field.
..81..
12 – Computer Science

(v) TABLE 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.
CREATE TABLE Student
(
Admno integer NOT NULL,
Firstname char(20),
Lastname char(20),
Gender char(1) DEFAULT=’M’, → Default constraint
Age integer CHECK (Age <= 19), → Check constraint
PRIMARY KEY (Firstname, Lastname) → Table constraint
);
2. Consider the following employee table. Write SQL commands for the questions.
(i) to (v).

EMP CODE NAME DESIG PAY ALLO WANCE


S1001 Hariharan Supervisor 29000 12000
P1002 Shaji Operator 10000 5500
P1003 Prasad Operator 12000 6500
C1004 Manjima Clerk 8000 4500
M1005 Ratheesh Mechanic 20000 7000
(i) To display the details of all employees in descending order of pay.
(ii) To display all employees whose allowance is between 5000 and 7000.
(iii) To remove the employees who are mechanic.
(iv) To add a new row.
(v) To display the details of all employees who are operators.
SQL COMMANDS:
(i) SELECT * FROM EMPLOYEE ORDER BY PAY DESC;
(ii) SELECT * FROM EMPLOYEE WHERE ALLOWANCE BETWEEN 5000 AND 7000;
(iii) DELETE FROM EMPLOYEE WHERE DESIG='MECHANIC';
(iv) INSERT INTO EMPLOYEE VALUES ('S1006', 'RAJESH', 'MECHANIC', 20000, 7000);
(v) SELECT * FROM EMPLOYEE WHERE DESIG='OPERATOR';

..82..
12 – Computer Science

3. What are the components of SQL? Write the commands in each.


SQL commands are divided into five categories:
i. DML - Data Manipulation Language
ii. DDL - Data Definition Language
iii. DCL - Data Control Language
iv. TCL - Transaction Control Language
v. DQL - Data Query Language
(i) DATA DEFINITION LANGUAGE
The Data Definition Language (DDL) consist of SQL statements used to define
the database structure or schema.
SQL commands which comes under Data Definition Language are:
➢ Create: To create tables in the database.
➢ Alter: Alters the structure of the database.
➢ Drop: Delete tables from database.
➢ Truncate: Remove all records from a table, also release the space occupied
by those records.
(ii) DATA MANIPULATION LANGUAGE
A Data Manipulation Language (DML) is a computer programming language
used for adding (inserting), removing (deleting), and modifying (updating) data in
a database. i.e., the data can be manipulated using a set of procedures which are
expressed by DML.
SQL commands which comes under Data Manipulation Language are :
➢ Insert: Inserts data into a table
➢ Update: Updates the existing data within a table.
➢ Delete: Deletes all records from a table, but not the space occupied by them.
(iii) DATA CONTROL LANGUAGE
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).
SQL commands which come under Data Control Language are:
➢ Grant: Grants permission to one or more users to perform specific tasks.
➢ Revoke: Withdraws the access permission given by the GRANT statement.

..83..
12 – Computer Science

(iv) TRANSACTIONAL CONTROL LANGUAGE


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.
SQL command which come under Transfer Control Language are:
➢ Commit: Saves any transaction into the database permanently.
➢ Roll back: restores the database to last commit state.
➢ Save point: temporarily save a transaction so that you can rollback.
(v) DATA QUERY LANGUAGE
The Data Query Language consist of commands used to query or retrieve data
from a database. One such SQL command in Data Query Language is
➢ Select: It displays the records from the table.
4. Construct the following SQL statements in the student table.
(i) SELECT statement using GROUP BY clause.
(ii) SELECT statement using ORDER BY clause.
If the Student table has the following data:
Admno Name Gender Age Place
100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 17 Bangalore
103 Ayush M 18 Delhi
104 Abinandh M 18 Chennai
105 Revathi F 19 Chennai
106 Devika F 19 Bangalore
107 Hema F 17 Chennai

(i) SELECT statement using GROUP BY clause.


➢ The GROUP BY clause is used with the SELECT statement to group the students
on rows or columns having identical values or divide the table in to groups.
➢ For example to know the number of male students or female students of a
class, the GROUP BY clause may be used.

..84..
12 – Computer Science

Syntax for the GROUP BY clause is


SELECT <column-names> FROM <table-name> GROUP BY <column-name>
HAVING [condition];
To apply the above command on the student table :
SELECT Gender FROM Student GROUP BY Gender;
The following command will give the below given result:

Gender
M
F
(ii) SELECT statement using ORDER BY clause.
➢ The ORDER BY clause in SQL is used to sort the data in either ascending or
descending based on one or more columns.
✓ By default ORDER BY sorts the data in ascending order.
✓ We can use the keyword DESC to sort the data in descending order and the
keyword ASC to sort in ascending order.
The ORDER BY clause is used as :
SELECT <column-name>[<column-name>…] FROM <table-name> GROUP BY
<column-name>,<column-name> ASC|DESC;
To display the students in alphabetical order of their names, use
SELECT * FROM Student ORDER BY Name;
The above student table is arranged as follows :

Admno Name Gender Age Place


104 Abinandh M 18 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 17 Bangalore
100 Ashish M 17 Chennai
103 Ayush M 18 Delhi
106 Devika F 19 Bangalore
107 Hema F 17 Chennai
105 Revathi F 19 Chennai

..85..
12 – Computer Science

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
(
EMPCODE CHAR(20),
NAME CHAR(20),
DESIG VARCHAR(20),
PAY INTEGER,
ALLOWANCE INTEGER,
PRIMARY KEY(EMPCODE) → Table constraint
);

..86..
13 PYTHON AND CSV FILES

I. Choose the best answer: (1 Mark)


1. A CSV file is also known as a ….
(A) Flat File (B) 3D File
(C) String File (D) Random File
2. The expansion of CRLF is
(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?
(A) py (B) xls (C) csv (D) os
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 5
5. The command used to skip a row in a CSV file is
(A) next() (B) skip() (C) omit() (D) bounce()
6. Which of the following is a string used to terminate lines produced by writer()method
of csv module?
(A) Line Terminator (B) Enter key
(C) Form feed (D) Data Terminator
7. What is the output of the following program? import csv
d=csv.reader(open('c:\PYPRG\ch13\city.csv'))
next(d)
for row in d:
print(row)
if the file called “city.csv” contain the following details
chennai, mylapore
mumbai, andheri
A) chennai,mylapore (B) mumbai,andheri
(C) chennai (D) chennai,mylapore
mumba mumbai,andheri

..87..
12 – Computer Science

8. Which of the following creates an object which maps data to a dictionary?


(A) listreader() (B) reader()
(C) tuplereader() (D) DictReader ()
9. Making some changes in the data of the existing file or adding more data is called
(A) Editing (B) Appending
(C) Modification (D) Alteration
10. What will be written inside the file test.csv using the following program
import csv
D = [['Exam'],['Quarterly'],['Halfyearly']]
csv.register_dialect('M',lineterminator = '\n')
with open('c:\pyprg\ch13\line2.csv', 'w') as f:
wr = csv.writer(f,dialect='M')
wr.writerows(D)
f.close()
(A) Exam Quarterly Halfyearly (B) Exam Quarterly Halfyearly
(C) E (D) Exam,
Q Quarterly,
H Halfyearly
II. Answer the following questions: (2 Marks)
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.
2. Mention the two ways to read a CSV file using Python.
1. Use the csv module’s reader function
2. Use the DictReader class.
3. Mention the default modes of the File.
The following are the default modes of the file.
(i) 'r' Open a file for reading. (default)
(ii) 't' Open in text mode. (default)
4. What is use of next() function?
The next() function returns the next item from the iterator. It can also be used to
skip a row of the csv file.

..88..
12 – Computer Science

5. How will you sort more than one column from a csv file? Give an example statement.
To sort by more than one column you can use itemgetter with multiple indices:
operator.itemgetter (1, 2)
Example:
Consider test.csv file:
name,age
Nandhini,20
Mathu,20
Nikhil,19
Code for multiple sort:
import csv, operator
data = csv.reader(open(‘d:\\test.csv’))
next(data)
sortedlist=sorted(data, key=operator.itemgetter(age, name))
for row in sorterdlist:
print(row)
Output:
[19,Nikhil]
[20,Mathu]
[20,Nandhini]
III. Answer the following questions: (3 Marks)
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 two different methods are
(i) open("sample.txt") as f:
(ii) with open()
The open() method is not entirely safe. If an exception occurs when you are
performing some operation with the file, the code exits without closing the file.
But “with open” statement ensures that the file is closed when the block inside
with is exited.

..89..
12 – Computer Science

2. Write a Python program to modify an existing file.


The “student.csv” file contains the following data.

Roll No Name City


1 Harshini Chennai
2 Adhith Mumbai
3 Dhuruv Bengaluru
The following program modifying the value of an existing row in student.csv
import csv
row = [‘2’, ‘Meena’,’Bangalore’]
with open(‘student.csv’, ‘r’) as readFile:
reader = csv.reader(readFile)
lines = list(reader)
lines[2] = row
with open(‘student.csv’, ‘w’) as writeFile:
writer = csv.writer(writeFile)
writer.writerows(lines)
readFile.close()
writeFile.close()
When we open the student.csv file with text editor, then it will show:

Roll No Name City


1 Harshini Chennai
2 Meena Bangalore
3 Dhuruv Bengaluru

3. Write a Python program to read a CSV file with default delimiter comma (,).
import csv
with open(‘student.csv’,'r') as readFile:
reader=csv.reader(readFile)
for row in reader:
print(row)
readFile.close( )

..90..
12 – Computer Science

4. What is the difference between the write mode and append mode.
‘w’ - write mode:
Open a file for writing. Creates a new file if it does not exist or truncates the file if it
exists.
‘a’ – append mode:
Open for appending at the end of the file without truncating it. Creates a new file if it
does not exist.
5. What is the difference between reader() and DictReader() function?
reader() DictReader()
The reader function is designed to take DictReader() creates an object which maps
each line of the file and make a list of all data to a dictionary.
columns.
csv.reader() works with list/tuple. csv.DictReader() works with dictionary

IV. Answer the following questions: (5 Marks)

1. Differentiate Excel file and CSV file.

Excel CSV
Excel is a binary file that holds CSV format is a plain text format with a
information about all the worksheets in series of values separated by commas.
a file, including both content and
formatting.
XLS files can only be read by applications CSV can be opened with any text editor
that have been especially written to in Windows like notepad, MS Excel,
read their format, and can only be OpenOffice, etc.
written in the same way.
Excel is a spreadsheet that saves files CSV is a format for saving tabular
with the extension “.xls” or “.xlsx” information into a delimited text file
with extension “.csv”
Excel consumes more memory while Importing CSV files can be much faster,
importing data. and it also consumes less memory.

..91..
12 – Computer Science

2. Tabulate the different file modes with its meaning.

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' Open 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.


There are two ways to read a CSV file.
1. Use the csv module’s reader function
2. Use the DictReader class.
1. CSV Module’s Reader Function:
➢ The csv.reader() method 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
quotes (" "), pipe (|) and comma (,).
The syntax for csv.reader() is
csv.reader(fileobject, delimiter, fmtparams)
where
✓ file object: passes the path and the mode of the file
✓ delimiter: an optional parameter containing the standard dialects like
, | etc can be omitted.
✓ fmtparams: optional parameter which help to override the default
values of the dialects like skip initial space, quoting etc. can be omitted.

..92..
12 – Computer Science

Example:
import csv
with open(‘Student.csv’,'r') as readFile:
reader=csv.reader(readFile)
for row in reader:
print(row)
readFile.close( )
2. Reading CSV File Into A Dictionary:
➢ To read a CSV file into a dictionary can be done by using DictReader which
creates an object which maps data to a dictionary.
➢ DictReader works by reading the first line of the CSV and using each comma
separated value in this line as a dictionary key.
➢ The columns in each subsequent row then behave like dictionary values and
can be accessed with the appropriate key.
Example:
import csv
filename="Student.csv"
myfile=csv.DictReader(open(‘Student.csv’,‘r‘))
for row in myfile:
print(dict(row))
4. Write a Python program to write a CSV File with custom quotes.
import csv
csvData = [[‘SNO’,’Items’], [‘1’,’Pen’], [‘2’,’Book’], [‘3’,’Pencil’]]
csv.register_dialect(‘myDialect’,delimiter=‘|’,quotechar = ‘”’,
quoting=csv.QUOTE_ALL)
with open(‘c:\pyprg\ch13\quote.csv’, ‘w’) as csvFile:
writer = csv.writer(csvFile, dialect=’myDialect’)
writer.writerows(csvData)
print(“writing completed”)
csvFile.close()

..93..
12 – Computer Science

5. Write the rules to be followed to format the data in a CSV file.


1. Each record (row of data) is to be located on a separate line, delimited by a line
break by pressing enter key. For example: 
xxx,yyy  ( denotes enter Key to be pressed)

2. The last record in the file may or may not have an ending line break. For example:
ppp, qqq 
yyy, xxx
3. There may be an optional header line appearing as the first line of the file with the
same format as normal record lines. For example:
field_name1,field_name2,field_name3 
aaa,bbb,ccc 
zzz,yyy,xxx CRLF (Carriage Return and Line Feed)
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. Each field may or may not be enclosed in double quotes. If fields are not enclosed
with double quotes, then double quotes may not appear inside the fields. For
example:
"Red","Blue","Green"  #Field data with doule quotes
Black,White,Yellow #Field data without doule quotes
6. Fields containing line breaks (CRLF), double quotes, and commas should be
enclosed in double-quotes. For example:
Red, “,”, Blue CRLF
Red, Blue , Green
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:
“Red, ” “Blue”, “Green”,
, , White

..94..

You might also like