12F Lab Manual 2022
12F Lab Manual 2022
COMPUTER
SCIENCE
Class XII
Name:
Class Sec______
XII-CS-Page 1
XII-CS-Page 2
INDEX
Page Teacher’s
S No Date Activity
No sign
1 LIST-SWAP
2 LIST – SEARCH
3 STRING-CAPITALIZE
4 LIST – UNIQUE VALUES
5 DICTIONARY – CREATE AND UPDATE
6 TUPLE
7 STRING-DELETE_CHAR
8 STRING-OCCURENCE
9 RANDOM NUMBER GENERATOR
10 TEXT FILE-#
11 TEXT FILE – DIFFERENT CHARACTERS
12 TEXT FILE - REMOVAL
13 BINARY FILE – CREATION AND SEARCH
14 BINARY FILE – CREATION AND UPDATION
15 CSV FILE
16 STACK - NUMBERS
17 STACK – BOOK DETAILS
18 STACK - STRING
19 TABLE - TEACHER
20 TABLES – PRODUCT AND CLIENT
21 TABLES – EMPLOYEE AND SALGRADE
22 TABLES – BOOKS AND ISSUED
23 TABLES – PRODUCT AND CLIENT
24 INTERFACE WITH PYTHON - 1
25 INTERFACE WITH PYTHON - 2
26 INTERFACE WITH PYTHON - 3
27 INTERFACE WITH PYTHON - 4
XII-CS-Page 3
OUTPUT
XII-CS-Page 4
TITLE : LIST-SWAP Date : __________________
def SWAP(lst):
for i in range(len(lst)-1):
if lst[i+1]%5==0:
lst[i],lst[i+1]=lst[i+1],lst[i]
for i in range(len(lst)):
print(lst[i],end=' ')
lst=[]
while True:
x=int(input("1.List Creation 2.Swap values 3.Exit"))
if x==1:
lst=eval(input("Enter a list"))
elif x==2:
SWAP(lst)
elif x==3:
break
else:
print("Invalid Code")
XII-CS-Page 5
OUTPUT
Date : ___________
Signature:_________________
XII-CS-Page 6
TITLE : LIST – SEARCH Date : _______________
2) Write a python program that uses a function SEARCH() which takes a list as parameter and
searches an element in a list and displays the position of the element present in the list and
its frequency .
Note: [List and search element should be entered by user]
def Search(lst):
x=int(input("Enter the element you want to search"))
found=False
for i in range(len(lst)):
if lst[i]==x:
found=True
print("Position ",i,end=' ')
if found:
print("Frequency",lst.count(x))
else:
print("Element not found")
lst=[]
while True:
x=int(input("1.List Creation 2.Search value 3.Exit"))
if x==1:
lst=eval(input("Enter a list:"))
elif x==2:
Search(lst)
elif x==3:
break
else:
print("Invalid Code")
XII-CS-Page 7
OUTPUT
XII-CS-Page 8
Date : ___________ Signature:_________________
3) Write a python program that uses the function CAPITALIZE() that takes in a string as a
parameter and capitalizes the first and last letters of each word in a given string.
def CAPITALIZE(String):
String=String.title()
lst=String.split()
String2=''
for i in lst:
String2=String2+i[:-1]+i[-1].upper()+' '
print(String2)
String=" "
while True:
x=int(input("1.String Creation 2.Capitalize 3.Exit"))
if x==1:
String=input("Enter String")
elif x==2:
CAPITALIZE(String)
elif x==3:
break
else:
print("Invalid Code")
XII-CS-Page 9
OUTPUT
XII-CS-Page 10
Date : ___________ Signature:_________________
4) Write a program using function called UNIQUE (List) that gets unique values from a list.
def Unique(lst):
lst2=[]
for i in lst:
if I not in lst2:
lst2.append(i)
print(lst2)
lst=[]
while True:
x=int(input("1.List Creation 2.Unique values 3.Exit"))
if x==1:
lst=eval(input("Enter elements"))
elif x==2:
Unique(lst)
elif x==3:
break
else:
print("Invalid Code")
XII-CS-Page 11
OUTPUT
XII-CS-Page 12
TITLE: DICTIONARY – CREATE AND UPDATE Date:______________
5) Write a Python script to print a dictionary where the keys are numbers between 1 and
15(both included) and the values are square of keys.
Sample Dictionary:
{1:1,2:4,3:9,4:16…15:225}
Also write a function SEARCH() that takes in the dictionary D as parameter and searches for a
particular key, if found returns the corresponding value, if not found , an error message will
be displayed.
def Search(d):
x=int(input("Enter a key value to search"))
if x in d.keys():
print("Key ",x," is found, the value is ",d.get(x))
else:
print("Key not found")
d={}
for i in range(1,16):
d[i]=i*i
print(d)
while True:
x=int(input("1.Search for a value 2.Exit"))
if x==1:
Search(d)
elif x==2:
break
else:
print("Invalid Code")
XII-CS-Page 13
OUTPUT
XII-CS-Page 14
TITLE: TUPLE Date:______________
6) Write a program using a function BUILD() to input any values for two tuples. Also
print them, interchange them and compare them with any two relational operators.
def BUILD():
global t1,t2
t1=eval(input("Enter tuple1"))
t2=eval(input("Enter tuple2"))
def PIC():
global t1,t2
print("Printing tuples")
print(t1)
print(t2)
print("Interchanging tuples")
t1,t2=t2,t1
print(t1)
print(t2)
print("Comparing tuples")
print(t1,t2)
print("t1>t2")
print(t1>t2)
print("t1<t2")
print(t1<t2)
print("t1==t2")
print(t1==t2)
print("t1!=t2")
print(t1!=t2)
t1=()
t2=()
while True:
x=int(input("1. Create Tuples 2.Print,Interchange and Compare tuples 3.Exit"))
if x==1:
BUILD()
elif x==2:
PIC()
elif x==3:
break
else:
print("Invalid Code")
XII-CS-Page 15
OUTPUT
XII-CS-Page 16
TITLE: STRING-DELETE_CHAR Date:__________________
7) Write a program that uses the function Deletechar() which takes two parameters – one is a
string and the other is a character. The function should create a new string after deleting all
occurrences of the character from the string and return the new string.
def Deletechar(String,Char):
String=String.replace(Char,'')
print(String)
String=" "
while True:
x=int(input("1.String Creation 2.Delete the character 3.Exit"))
if x==1:
String=input("Enter String")
elif x==2:
Char=input("Enter a character to remove from string")
Deletechar(String,Char)
elif x==3:
break
else:
print("Invalid Code")
XII-CS-Page 17
OUTPUT
XII-CS-Page 18
TITLE: STRING-OCCURENCE Date:__________
8) Write a program using a function OCCUR() to print the number of occurrences of a substring
into a line using find() function.
def Occur(String,Substring):
Count=String.count(Substring)
print(Count)
String=" "
while True:
x=int(input("1.String Creation 2.Occurence of Substring 3.Exit"))
if x==1:
String=input("Enter String")
elif x==2:
Substring=input("Enter substring to find occurences from string")
Occur(String,Substring)
elif x==3:
break
else:
print("Invalid Code")
XII-CS-Page 19
OUTPUT
XII-CS-Page 20
TITLE : RANDOM NUMBER GENERATOR. Date:_______________
9) Write a program to play a dice game that generates 3 random numbers between 1 and 6. If all
the three random numbers are equal, the score is increased by 50 points and the program
quits. If any two random numbers are equal, then score is increased by 25 points otherwise,
score is increased by 10 points.
The program runs as long as the user wants to continue.
XII-CS-Page 21
OUTPUT
XII-CS-Page 22
TEXT FILE-# Date:__________
10) Read a text file line by line and display each word separated by a #.
def hash():
with open('conf.txt') as file:
s=file.readline()
while(s):
i=s.split()
print('#'.join(i))
s=file.readline()
hash()
XII-CS-Page 23
OUTPUT
XII-CS-Page 24
TITLE: TEXT FILE-DIFFERENT CHARACTERS Date:____________
11) Read a text file and display the number of vowels /consonants /
uppercase / lowercase characters in the file.
def VCLU():
V=0
C=0
L=0
U=0
with open('vowels.txt') as file:
s=file.read()
for i in s:
if i in 'aeiouAEIOU':
V+=1
if not i in 'aeiouAEIOU':
C+=1
if i.islower():
L+=1
if i.isupper():
U+=1
print("Vowels:",V,"Consonants:",C,"Lowercase letters:",L,"Uppercase letters:",U)
VCLU()
XII-CS-Page 25
OUTPUT
XII-CS-Page 26
TITLE: TEXT FILE – REMOVAL Date:________________
12) Remove all the lines that contain the character 'a' in a file and write it to another file.
def Aa():
with open('conf2.txt','r') as In:
with open('temp.txt','w') as out:
s=In.readlines()
l1=[]
for i in s:
if 'a' in i or 'A' in i:
out.write(i)
else:
l1.append(i)
with open('conf2.txt','w+') as In:
with open('temp.txt','r') as out:
In.seek(0)
In.write(''.join(l1))
print("\nOriginal file")
In.seek(0)
print(In.read())
print("\nCopied file")
print(out.read())
Aa()
XII-CS-Page 27
OUTPUT
XII-CS-Page 28
TITLE: BINARY FILE – CREATION AND SEARCH Date:________
13) Create a binary file with roll number, name and marks. Search for a given roll number and
display the name, if not found display appropriate message.
import pickle
def Append():
with open('student.dat','ab')as file:
while True:
stud=[]
Rollno=int(input("Enter rollno "))
Name=input("Enter Name ")
Marks=eval(input("Enter marks "))
stud=[Rollno,Name,Marks]
pickle.dump(stud,file)
ans=input("Continue(y/n)")
if ans=='n' or ans=='N':
break
def Search():
r=int(input("enter rollno to search"))
found=False
with open('student.dat','rb')as file:
while True:
try:
stud=pickle.load(file)
if stud[0]==r:
print("Name : ",stud[1])
print("Marks: ",stud[2])
found=True
except EOFError :
break
if not found:
print("Sorry, record not found")
while True:
opt=int(input("1.Append 2.Search 3.Exit"))
if opt==1:
Append()
elif opt==2:
Search()
elif opt==3:
XII-CS-Page 29
break
else:
print("Invalid Code")
XII-CS-Page 30
OUTPUT
XII-CS-Page 31
TITLE: BINARY FILE – CREATION AND UPDATION Date:_________________
14) Create a binary file with roll number, name and marks. Input a roll number and search for it in
the file, if found, update the marks to new marks, otherwise , display an error message.
import pickle
def Append():
with open('student.dat','ab')as file:
while True:
stud=[]
Rollno=int(input("Enter rollno"))
Name=input("Enter Name")
Marks=eval(input("Enter marks"))
stud=[Rollno,Name,Marks]
pickle.dump(stud,file)
ans=input("Continue(y/n)")
if ans=='n' or ans=='N':
break
def Update():
file=open('student.dat','rb')
r=int(input("Enter rollno of the student whose mark is to be updated:"))
found=False
lst2=[]
while file:
try:
lst=pickle.load(file)
lst2.append(lst) #copying in another list
except EOFError:
break
file.close()
for i in lst2:
if i[0]==r:
print("Old record")
print(i)
i[2]=float(input("Enter new marks")) #update marks
found=True
file=open('student.dat','wb')
print("Updated data:")
for i in lst2:
pickle.dump(i,file)
print(i)
file.close()
if found==False:
print("Record Not found")
while True:
opt=int(input("1.Append 2.Update 3.Exit"))
if opt==1:
Append()
XII-CS-Page 32
elif opt==2:
Update()
elif opt==3:
break
else:
print("Invalid Code")
OUTPUT
XII-CS-Page 33
Date : ___________ Signature:_________________
15) Create a CSV file (Emp.csv) for N employees where N is input by the user with following
details – Empid, Empname,Basic_Pay and HRA(House Rent Allowance). Read the same file and
calculate Gross_Pay(Basic_Pay+HRA) for all employees and display the same.
import csv
fields=['Empid', 'Empname','Basic_Pay','HRA(House Rent Allowance)']
def Write():
with open('employee.csv','w',newline='') as f:
Writer=csv.writer(f)
Writer.writerow(fields)
n=int(input("Enter how many records"))
for i in range(n):
lst=eval(input("Enter Empid, Empname,Basic_Pay and HRA(House Rent Allowance)"))
Writer.writerow(lst)
def Read():
with open('employee.csv','r') as f:
Reader=csv.reader(f)
cols=next(Reader)
print(' '.join(cols))
for i in Reader:
Grosspay=eval(i[2])+eval(i[3])
print(' '.join(i),Grosspay)
Write()
Read()
XII-CS-Page 34
OUTPUT
XII-CS-Page 35
Date : ___________
Signature:_________________
16) Write a program to create a list of any value, use stack as data structure and perform
push(),pop(),display activities using a menu driven program.
Program
lst=[]
Top=None
def push(x):
global lst,Top
lst.append(x)
Top=len(lst)-1
def chkstatus():
global lst
if lst==[]:
return 0
else:
return 1
def pop():
global lst,Top
if chkstatus():
print('\n\t\t\tDeleted element :',lst.pop())
if len(lst)==0:
Top=None
else:
Top=len(lst)-1
else:
print('\n\t\t\tUnderflow')
XII-CS-Page 36
def display():
global lst,Top
if chkstatus():
print('\n\t\t\tElements available in the list ')
for i in range(Top,-1,-1):
print('\t\t\t',lst[i])
else:
print('\n\t\t\tUnderflow')
XII-CS-Page 37
OUTPUT
XII-CS-Page 38
DATE:_______________ SIGNATURE:__________________________
17) Write a program using stack to store details about the book(book number, book name, book
price) and use a menu driven program to push(), pop() contents into the stack data structure.
Program
book=[]
Top=None
def push():
global book, Top
bookno=int(input('Enter book number :'))
XII-CS-Page 39
bname=input('Enter book name :')
bprice=float(input('Enter book price :'))
book.append([bookno,bname,bprice])
Top=len(book)-1
def pop():
global book,Top
if chkstatus():
print('-'*65)
print('\t\t\tElement deleted')
print('\t\t\tBook number :',book[Top][0])
print('\t\t\tBook name :',book[Top][1])
print('\t\t\tBook prie :',book[Top][2])
print('-'*65)
book.pop()
if len(book)==0:
Top=None
else:
Top=len(book)-1
else:
print('Underflow')
def chkstatus():
if len(book)==0:
return 0
else:
return 1
while True:
print('-'*65)
print('\t\t\tMenu choices')
print('\t\t\t1 - Push - to add book')
print('\t\t\t2 - Pop - to delete book')
print('\t\t\t3 - Exit ')
print('-'*65)
a=int(input('\t\t\tEnter your choice :'))
if a == 1:
push()
elif a==2:
pop()
elif a==3:
break
else:
print('End of program')
XII-CS-Page 40
break
XII-CS-Page 41
OUTPUT
XII-CS-Page 42
DATE:_______________ SIGNATURE:__________________________
18) Write a program using stack to characters in a stack. This problem is to demonstrate how stack
can be applied to reverse a string and check if it a palindrome or not.
Program
str=''
Top=None
def push(chr):
global str,Top
str=str+chr
Top=len(str)-1
XII-CS-Page 43
def chk(str):
if len(str)==0:
return 0
else:
return 1
def pop():
global str,Top
if chk(str):
ch=str[Top]
str=str[:Top]
Top=len(str)-1
return ch
else:
return -1
str1=''
while True:
print('-'*65)
print('\t\t\tMenu choices')
print('\t\t\t1 - Push')
print('\t\t\t2 - Pop')
print('\t\t\t3 - Exit')
print('-'*65)
ch = int(input('\t\t\tEnter your choice :'))
if ch == 1:
ch=input('\t\t\tEnter any character :')
push(ch)
elif ch==2:
ch=pop()
if ch!=-1:
print(ch,' character returned')
str1+=ch
else:
print('Underflow')
if str1== str1[::-1]:
print(str1,'Palindrome')
else:
print(str1,'not a palindrome')
break
elif ch==3:
break
XII-CS-Page 44
else:
print('Invalid choice ')
XII-CS-Page 45
OUTPUT
XII-CS-Page 46
DATE:_______________ SIGNATURE:__________________________
SQL
XII-CS-Page 47
Field Name Data type
T_Id Int
Name Varchar(25)
Age Int
Department Varchar(25)
Date_of_join Date
Salary Int
Gender Char(1)
Table:Teacher
Create table teacher(T_id int, Name varchar(25), Age int, Department varchar(25), Date_of_join
date,
Salary int, Gender char(1));
XII-CS-Page 48
insert into teacher values(4,’Sangeetha’,35,’History’,’2015-07-01’,40000,’F’);
iii) List the names of all teachers with their date of joining in ascending order.
Select name, date_of_join from teacher order by date_of_join;
v) Display T_Id, Name, Department of Female teachers whose name ends with ‘a’.
select T_Id, Name, Department from teacher where Name like’%a’;
XII-CS-Page 49
XII-CS-Page 50
OUTPUT
XII-CS-Page 51
DATE:_______________ SIGNATURE:__________________________
TABLE - PRODUCT
ii) Increase the price of all the products in product table by 10%.
update product set price = price + price * .10;
iii) Display the Product name, Manufacturer, Expiry Date of all the products that
expired on or before ‘2010-12-31’.
select productname, manufacturer, expirydate from product where expirydate
<= ‘2010-12-31’;
iv) Display P_Id, Client Name, City of all the Clients and their corresponding
ProductName sold.
select client.P_Id, Clientname, city from client, product where client.P_Id =
product.P_Id;
XII-CS-Page 52
select count(*) “Product count”, manufacturer from product group by
manufacturer;
OUTPUT
XII-CS-Page 53
DATE:_______________ SIGNATURE:__________________________
Table : EMPLOYEE
Table : SALGRADE
ii) Display ECode, Name, Total Salary(Salary + HRA) of those employees who joined before
2006.
select Ecode, Name, Salary + HRA as ‘Total Salary’ from employee, salgrade where DOJ
< ‘2006-01-01’ and employee.sgrade = salgrade.sgrade;
iv) Display Name and Desig of those employees who are born between 01-Jan-1982 and 20-
Feb-1983.
select name. desig from employee where DOB between ‘1982-01-01’ and ‘1983-02-20’;
XII-CS-Page 54
OUTPUT
XII-CS-Page 55
DATE:_______________ SIGNATURE____________________
Table : BOOKS
Table : ISSUED
BOOK_ID QTY_ISSUED
P0001 13
N0002 5
K0002 21
Execute SQL commands on the basis of these two tables – Books and Issued.
XII-CS-Page 56
OUTPUT
DATE:_______________ SIGNATURE:__________________________
XII-CS-Page 57
TITLE - PRODUCT AND CLIENT Date: _________________
TABLE - PRODUCT
TABLE – CLIENT
i) Display product name and price of all products whose price is in the range 50 to 150.
Select productname, price from product where price between 50 and 150;
iii) Display product name, manufacturer, price for all products that are not giving any
discount.
Select productname, manufacturer, price from product where discount is NULL;
iv) Display details of all products whose name has letter ‘O’ or ‘o’ somewhere in it.
Select * from product where productname like ‘%o%’;
v) Display clientname, city, P_Id and product name for all clients whose city is Delhi.
XII-CS-Page 58
OUTPUT
XII-CS-Page 59
DATE:_______________ SIGNATURE:__________________________
TITLE: INTERFACE PYTHON WITH SQL – TABLES – EMP AND DEPT Date : ____________
Table : Emp
Table:Dept
Using the Python interface , connect the database and execute the following commands.
a) Display employee’s name,job and location of those drawing a salary that is greater than the
user's input.
b) Display the dept no, department name, count of employees and mgr(manager) code which is
having more than n employees where n is input by the user.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="sample",database="r
ecord2022")
mycursor=mydb.cursor()
def Display():
XII-CS-Page 60
sal=int(input("Enter salary"))
mycursor.execute("select ename,job,sal,loc from emp,dept where sal> " + str(sal)+" and
emp.deptno=dept.deptno")
rows=mycursor.fetchall()
print(" ename\tjob\t\tsal\t\tloc")
for i in rows:
print(i[0],i[1],i[2],i[3],sep='\t')
def Count():
n=int(input("Enter no of employees"))
mycursor.execute("select dept.deptno,dname,count(*),mgr from dept,emp where
dept.deptno=emp.deptno group by mgr having count(*) > " + str(n))
rows=mycursor.fetchall()
print("DeptNo\tDeptName\tNoofEmp\tManagerCode")
for i in rows:
print(i[0],i[1],i[2],i[3],sep='\t')
Display()
print()
Count()
XII-CS-Page 61
XII-CS-Page 62
OUTPUT
XII-CS-Page 63
Date : ___________ Signature:_________________
TITLE : INTERFACE PYTHON WITH SQL – TABLES – EMP AND DEPT Date : __________
25) Using the same Emp and Dept tables as mentioned above, execute the following commands
using python interface.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="sample",database="record2
022")
mycursor=mydb.cursor()
def Update():
mycursor.execute("update emp set comm = sal * .10 where comm is NULL")
mydb.commit()
print("Updated successfully")
mycursor.execute("select empno,ename,comm from emp")
rows=mycursor.fetchall()
print(" Empno\tEmpname\tCommission")
for i in rows:
print(i[0],i[1],i[2],sep='\t')
def Delete():
eno=input("Enter Empno to delete")
mycursor.execute("delete from emp where empno=" + eno)
mydb.commit()
print("Record Successfully deleted")
mycursor.execute("select empno,ename from emp")
rows=mycursor.fetchall()
print("Empno EmpName")
for i in rows:
print(i[0],i[1])
Update()
print()
Delete()
XII-CS-Page 64
OUTPUT
XII-CS-Page 65
Date : ___________ Signature:_________________
TITLE: INTERFACE PYTHON WITH SQL – TABLES – EMP AND DEPT Date : __________
26) Using the same Emp and Dept tables as mentioned above, execute the following commands
using python interface.
Program:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="sample",database="record2
022")
mycursor=mydb.cursor()
def Insert():
mycursor.execute("insert into emp values(8555,'Hanks','Analyst',7566,'1981-12-
24',110000.00,NULL,30)")
mydb.commit()
print("Inserted successfully")
def Order():
x=input("enter the field to sort ")
y=input("A/D(Ascending/Descending")
if y=='A' or y=='a':
mycursor.execute("select * from emp order by "+x)
elif y=='D' or y=='d':
mycursor.execute("select * from emp order by "+x+ " desc")
rows=mycursor.fetchall()
for i in rows:
print(i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7])
Insert()
print()
Order()
XII-CS-Page 66
OUTPUT
XII-CS-Page 67
Date : ___________ Signature:_________________
TITLE : INTERFACE PYTHON WITH SQL – TABLES – EMP AND DEPT Date : __________
Using the same Emp and Dept tables as mentioned above, execute the following commands using
python interface.
a) Display the details of emp table who joined in the year 1982.
b) Display Empno, Ename and Sal of those employees who work in Dallas.
Program:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="sample",database="record2
022")
mycursor=mydb.cursor()
def Date():
mycursor.execute("select * from emp where hiredate like '1982%'")
rows=mycursor.fetchall()
for i in rows:
print(i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7])
def Join():
mycursor.execute("select empno,ename,sal from emp,dept where emp.deptno = dept.deptno and
loc='Dallas'")
rows=mycursor.fetchall()
for i in rows:
print(i[0],i[1],i[2])
Date()
print()
Join()
XII-CS-Page 68
OUTPUT
XII-CS-Page 69
Date : ___________ Signature:_________________
XII-CS-Page 70