0% found this document useful (0 votes)
111 views70 pages

12F Lab Manual 2022

The document is a preparatory lab manual for the computer science class of Chennai Public School for the 2022-2023 academic year. It contains 27 activities covering topics like lists, strings, files, and databases. Each activity contains sample code to demonstrate the concept and has space for students to record the date and teacher's signature when completing the activity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views70 pages

12F Lab Manual 2022

The document is a preparatory lab manual for the computer science class of Chennai Public School for the 2022-2023 academic year. It contains 27 activities covering topics like lists, strings, files, and databases. Each activity contains sample code to demonstrate the concept and has space for students to record the date and teacher's signature when completing the activity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 70

CHENNAI PUBLIC SCHOOL

COMPUTER
SCIENCE
Class XII

Preparatory Lab Manual


(2022-2023)

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

Date : ___________ Signature:_______

XII-CS-Page 4
TITLE : LIST-SWAP Date : __________________

1) A list Num contains the following elements


3,25,13,6,35,8,14,45
Write a program using function SWAP() that takes in a list as a parameter and swaps the
content with the next value divisible by 5 so that the resultant list will look like:
25,3,13,35,6,8,45,14

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:_________________

TITLE : STRING-CAPITALIZE Date : ________________

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:_________________

TITLE: LIST – UNIQUE VALUES Date:________________

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

Date : ___________ Signature:_________________

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

Date : ___________ Signature:_________________

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

Date : ___________ Signature:_________________

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

Date : ___________ Signature:_________________

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

Date : ___________ Signature:_________________

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.

from random import *


score=0
while True:
a=randint(1,6)
b=randint(1,6)
c=randint(1,6)
print("a=",a,"b=",b,"c=",c)
if a==b==c:
score+=50
print("adding 50")
break
elif a==b or b==c or a==c :
score+=25
print("adding 25")
else:
score+=10
print("adding 10")
print("The score is ",score)
ans=input("Continue(y/n)?")
if ans=='n' or ans=='N':
break

XII-CS-Page 21
OUTPUT

Date : ___________ Signature:_________________

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

Date : ___________ Signature:_________________

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

Date : ___________ Signature:_________________

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

Date : ___________ Signature:_________________

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

Date : ___________ Signature:_________________

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:_________________

TITLE: CSV FILE Date:________________

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:_________________

TITLE : STACK – NUMBERS Date:_____________________

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:__________________________

TITLE : STACK – BOOK DETAILS Date:_____________________

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:__________________________

TITLE : STACK - STRING Date:_____________________

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

TITLE : TEACHER TABLE Date : ___________________

19) Create a table TEACHER with the following structure:

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)

Insert following records:

Table:Teacher

T_I Name Ag Department Date_of_join Salar Gender


D e y
1 Jugal 34 Computer Sc 10-01-2017 1200 M
0
2 Sharmilla 31 History 24-03-2008 2000 F
0
3 Sandeep 32 Mathematics 12-12-2016 3000 M
0
4 Sangeeta 35 History 01-07-2015 4000 F
0
5 Rakesh 42 Mathematics 05-09-2007 2500 M
0
6 Shyam 50 History 27-06-2008 3000 M
0
7 Shiv Om 44 Computer Sc 25-02-2017 2100 M
0
8 Shalakha 33 Mathematics 31-07-2018 2000 F
0

Create table teacher(T_id int, Name varchar(25), Age int, Department varchar(25), Date_of_join
date,
Salary int, Gender char(1));

insert into teacher values(1,’Jugal’,34,’Computer Sc’,’2017-01-10’,12000,’M’);

insert into teacher values(2,’Sharmila’,31,’History’,’2008-03-24’,20000,’F’);

insert into teacher values(3,’Sandeep’,32,’Mathematics’,’2016-12-12’,30000,’M’);

XII-CS-Page 48
insert into teacher values(4,’Sangeetha’,35,’History’,’2015-07-01’,40000,’F’);

insert into teacher values(5,’Rakesh’,42,’Mathematics’,’2007-09-05’,25000,’M’);

insert into teacher values(6,’Shyam’,50,’History’,’2008-06-27’,30000,’M’);

insert into teacher values(7,’Shiv Om’,44,’Computer Sc’,’2007-02-25’,21000,’M’);

insert into teacher values(8,’Shalakha’,33,’Mathematics’,’2018-07-31’,20000,’F’);

Execute SQL commands for the following queries.

i) Show all information about teachers of History department.


select * from teacher where department = ‘History’;

ii) List different departments of the teachers.


select distinct department from teacher;

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;

iv) Display all details of teachers who have joined in 2017.


select * from teacher where date_of_join like’2017%’;

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:__________________________

TITLE : PRODUCT AND CLIENT Date: ___________________

20) Consider the following two tables Product and Client:

TABLE - PRODUCT

P_ID ProductName Manufacturer Price ExpiryDate


TP01 TALCUM POWDER LAK 40 2011-06-26
FW05 FACE WASH ABC 45 2010-12-01
BS01 BATH SOAP ABC 55 2010-09-10
SH06 SHAMPOO XYZ 120 2012-04-09
FW12 FACE WASH XYZ 95 2010-08-15
TABLE - CLIENT

C_ID ClientName City P_ID


1 Cosmetic Shop Delhi FW05
6 Total Health Mumbai BS01
12 Live Life Delhi SH06
15 Pretty One Delhi FW05
16 Dreams Bengaluru TP01
14 Expressions Delhi NULL

Execute SQL statements for the following queries.


i) Display client name and city of all Mumbai and Delhi based clients in Clients table.
select clientname, city from client where city in (‘DELHI’,’MUMBAI’);

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;

v) Display total number of products along with manufacturer, manufacturer-wise.

XII-CS-Page 52
select count(*) “Product count”, manufacturer from product group by
manufacturer;

OUTPUT

XII-CS-Page 53
DATE:_______________ SIGNATURE:__________________________

TITLE - EMPLOYEE AND SALGRADE Date: ___________________

21) Consider the following tables – Employee and Salgrade.

Table : EMPLOYEE

ECODE NAME DESIG SGRADE DOJ DOB


101 Abdul Ahmed EXECUTIVE S03 23-Mar-2003 13-Jan-1980
102 Ravi Chander HEAD-IT S02 12-Feb-2010 22-Jul-1987
103 John Ken RECEPTIONIST S03 24-Jun-2009 24-Feb-1983
105 Nazar Ameen GM S02 11-Aug-2006 03-Mar-1984
108 Priyam Sen CEO S01 29-Dec-2004 19-Jan-1982

Table : SALGRADE

SGRADE SALARY HRA


S01 S6000 18000
S02 32000 12000
S03 24000 8000

Execute the SQL commands for the following queries.

i) Display the details of all Employees in descending order of DOJ.


select * from employee order by DOJ desc;

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;

iii) Display employee name and salary grade wise.


select name, salary from employee, salgrade where 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’;

v) Display total number of employees in each grade.


select count(*) “No of Employees” from employee group by sgrade;

XII-CS-Page 54
OUTPUT

XII-CS-Page 55
DATE:_______________ SIGNATURE____________________

TITLE : BOOKS AND ISSUED Date: ___________________

22) Consider the following tables – Books and Issued.

Table : BOOKS

Book_id Book_name Author_name Publishers Price Type Qty


k0001 Let Us C Sanjay Mukharjee EPB 450 Comp 35
P0001 Genuine J Mukhi First Publ. 755 Fiction 24
M0001 Mastering C++ Kantkar EPB 165 Comp 60
Q0002 VC++ advance P.Purohit TDH 250 Comp 45
K0002 Programming with Sanjeet First Publ. 150 Fiction 30
Python

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.

i) Show the books of ‘FIRST PUBL.’ Publishers written by Sanjeev.


Select * from books where author_name = ‘Sanjeev’ and publishers = ‘First Publ.’;
ii) Display Book_name,cost and of all books published by EPB.
Select book_name, price*qty ‘Cost’ from books where publishers = ‘EPB’;
iii) Change the data type of price to Decimal(7,2)
Alter table Books MODIFY price decimal(7,2);
iv) Depreciate (reduce) the price of all fiction books by 5%.
Update Books set price=price - price* 0.05 where type = ‘Fiction’;
OR
Update Books set price=price*0.95 where type = ‘Fiction’;
v) Show type and total cost of books of each type.
Select type, sum(price*qty) “Total Cost” from Books group by type;
vi) Display the Book_id,Book_name , Publisher and price of the books, more than 5 copies of
which have been issued.
Select books.bookid,book_name,publishers,price from books,issued where
books.book_id = issued.book_id and quantity_issued > 5;

XII-CS-Page 56
OUTPUT

DATE:_______________ SIGNATURE:__________________________

XII-CS-Page 57
TITLE - PRODUCT AND CLIENT Date: _________________

23) Consider the following tables – Product and Client

TABLE - PRODUCT

P_ID ProductName Manufacturer Price ExpiryDate


TP01 TALCUM POWDER LAK 40 2011-06-26
FW05 FACE WASH ABC 45 2010-12-01
BS01 BATH SOAP ABC 55 2010-09-10
SH06 SHAMPOO XYZ 120 2012-04-09
FW12 FACE WASH XYZ 95 2010-08-15

TABLE – CLIENT

C_ID ClientName City P_ID


1 Cosmetic Shop Delhi FW05
6 Total Health Mumbai BS01
12 Live Life Delhi SH06
15 Pretty One Delhi FW05
16 Dreams Bengaluru TP01
14 Expressions Delhi NULL

Execute SQL commands on the basis of these two tables

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;

ii) Display details of products whose manufacturer is either XYZ or ABC.


Select * from product where manufacturer in (‘XYZ’,’ABC’);

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.

Select clientname, city, client.p_id, productname from client, product where


client.p_id = product.p_id and city = ‘Delhi’;

XII-CS-Page 58
OUTPUT

XII-CS-Page 59
DATE:_______________ SIGNATURE:__________________________

TITLE: INTERFACE PYTHON WITH SQL – TABLES – EMP AND DEPT Date : ____________

24) Consider the following table – Emp and Dept

Table : Emp

Empno EName Job Mgr Hiredate Sal Comm DeptNo


7369 SMITH CLERK 7902 1980-12-17 80000.00 NULL 20
7566 JONES MANAGER 7839 1981-04-02 29750.00 NULL 20
7698 BLAKE MANAGER 7839 1981-05-01 28500.00 NULL 30
7782 CLARK MANAGER 7839 1981-06-09 84500.00 NULL 10
7788 SCOTT ANALYST 7566 1982-12-09 75000.00 NULL 20
7844 TURNER SALESMAN 7698 1981-09-08 15000.00 0.0 30
7900 JAMES CLERK 7698 1981-12-03 90950.00 NULL 30
7934 MILLER CLERK 7782 1982-01-23 15000.00 NULL 10
7499 ALLEN SALESMAN 7698 1981-02-20 160000.00 30000.00 30
7521 WARD SALESMAN 7698 1981-02-22 115250.00 50000.00 30
7839 KING PRESIDENT NULL 1981-11-17 250000.00 NULL 10
7876 ADAMS CLERK 7788 1983-01-12 111100.00 NULL 20
7902 FORD ANALYST 7566 1981-12-03 130000.00 NULL 20

Table:Dept

DeptNo DName Loc


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

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.

a) Give 10% commission on salary for those whose commission is NULL.


b) Delete a particular employee’s record where empno is input by the user.

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.

a) Insert following record into emp table.


8555,'Hanks','Analyst',7566,'1981-12-24',110000.00,NULL,30
b) Sort the records of employee based on the field input by user and also ‘a’ , ascending or ‘d’,
descending.

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

You might also like