12CS em 2
12CS em 2
..47..
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, ab))
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
..51..
9 LISTS, TUPLES, SETS AND DICTIONARY
..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
Output:
[1,2,3,4,5]
[5,4,3,2,1]
3. What will be the output of the following code?
list = [2x 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
..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
..60..
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
..65..
11 DATABASE CONCEPTS
..66..
12 – Computer Science
..67..
12 – Computer Science
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
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
Doctor Patient
Diagnosis
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(
)
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
..73..
12 – Computer Science
Course
Big Data
R language
Python Programming
..74..
12 – Computer Science
Table A Table B
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
..76..
12 – Computer Science
..77..
12 STRUCTURED QUERY LANGUAGE (SQL)
..78..
12 – Computer Science
..79..
12 – Computer Science
Place
Madurai
Chennai
Coimbatore
..80..
12 – Computer Science
..82..
12 – Computer Science
..83..
12 – Computer Science
..84..
12 – Computer Science
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 :
..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
..87..
12 – Computer Science
..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
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
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
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)
..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
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..