You are on page 1of 24

CH.

CHHABIL DASS PUBLIC


SCHOOL

Computer Science Practical File


Submitted by – Gaurang Garg
Class – XII A
Submitted to – Amit Sir
Practical File Programs -2022-23
Class XII-CS (083)
INDEX
SECTION – A ( PYTHON )
S.NO PROGRAM DATE OF SIGN
SUBMISSION
1. Write a UDF in Python , it will take a number as a
function argument . Function check and display
given number if prime or not.
2. Write a UDF in python, it will take a string as
function argument. Function count and display the
number of vowels ,consonants, uppercase, lowercase
characters in string.
3. Write a UDF in python, it will take two arguments
list(sequence of elements) and finding element .
Function search and return 1 if element is present in
the given list otherwise return -1 . Using Binary
search.
4. Write a function in PYTHON that counts the number
of “Me” or “My” words present in a text file
“DIARY.TXT”.
5. Write a function in PYTHON to read the contents of a
text file “Places.Txt” and display all those lines on
screen which are either starting with ‘P’ or with ‘S’.
6. Write a function EUCount() in PYTHON, which
should read each character of a text file IMP.TXT,
should count and display the occurrences of
alphabets E and U (including small cases e and u
too).
7. Write a function in PYTHON to count the number of
lines ending with a vowel from a text file
“STORY.TXT’.
8. Write a function copy() that will copy all the words
starting with an uppercase alphabet from an existing
file “FAIPS.TXT” to a new file “DPS.TXT”.
9. Write a function in PYTHON to search for a BookNo
from a binary file “BOOK.DAT”, assuming the binary
file is containing the records of the following type:
("BookNo", "Book_name"). Assume that BookNo is
an integer.
10. Write a menu-driven program to perform all the basic
operations using dictionary on student binary file
such as inserting, reading, updating, searching and
deleting a record.

Write a function in PYTHON to search for a BookNo


from a binary file “BOOK.DAT”, assuming the binary
file is containing the records of the following type:
{"BookNo":value, "Book_name":value}. Assume that
BookNo is an integer.
12. Write a menu-driven program implementing user-
defined functions to perform different functions on a
csv file “student” such as:
(a) Write a single record to csv.
(b) Write all the records in one single go onto the
csv.
(c) Display the contents of the csv file.
13. Create a CSV file by entering user-id and password,
read and search the password for given userid.
14. Write a function in Python for PushS(List) and for
PopS(List) for performing Push and Pop operations
with a stack of List containing integers.
15. Write a program to create a stack called student, to
perform the basic operations on stack using list. The
list contains two data values called roll number and
name of
student. Notice that the data manipulation
operations are performed as per the rules of a stack.
Write the following functions :
• PUSH ( ) - To push the data values (roll no. and
name) into the stack.
• POP() - To remove the data values from the
stack.
• SHOW() - To display the data values from the
stack.
16. ABC Infotech Pvt. Ltd. needs to store, retrieve and
delete
the records of its employees. Develop an interface
that
provides front-end interaction through Python, and
stores
and updates records using MySQL.
(a) Write a UDF to create a table ‘EMPLOYEE’ through
MySQL- Python Connectivity.
(b) Write a UDF to add/insert employee data into the
‘EMPLOYEE’ table through MySQL-Python
Connectivity.
(c) Write a UDF to fetch and display all the records
from
EMPLOYEE table .
(d) Write a UDF to update the records of employees
by
increasing salary by 1000 of all those employees
who
are getting less than 80000.
(e) Write a UDF to delete the record on the basis of
Employee eno.
Write a menu driven program to perform all
operations.
.
ANSWERS
SECTION-A (PYHTON)

1.
def check(a):
c=0
for i in range(2,a):
if a%i==0:
c=c+1
if c==0:
print("The given number is prime")
else:
print("The given number is not prime")

a=int(input("Enter the number to check"))


check(a)

result = fun(list, x)
print(result)

2.
def count(a):
v=0
c=0
u=0
l=0
for i in a:
if i in "AEIOUaeiou":
v=v+1
elif i not in "AEIOUaeiou" and i.isalpha():
c=c+1
for i in a:
if i.isupper():
u=u+1
elif i.islower():
l=l+1
print("Number of vowels-",v)
print("Number of consonants-",c)
print("Number of Uppercase letters-",u)
print("Number of Lowercase letters-",l)

a=input("Enter the string to count for


vowel,consonant,uppercase,lowercase")
count(a)

3.
def fun(list, x):

list.sort()
low = 0
high = len(list) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if list[mid] < x:
low = mid + 1
elif list[mid] > x:
high = mid - 1
else:
return 1
return -1
list = [23,46,2,4,5]
x = int(input("Enter the element to search: "))

4.
def count():
f=open("DIARY.TXt")
a=f.read()
b=a.lower()
me=0
my=0
for i in b:
if i=="me":
me=me+1
if i=="my":
my=my+1
print("Number of me-",me)
print("Number of my-",my)

count()

5.
def fun():
f=open("Places.txt", "r")
lines=f.readlines()
for i in lines:
if i[0]=="P" or i[0]=="S":
print(i)
f.close()
fun()

6.
def EUCount():
f=open("IMP.TXT", "r")
str=f.read()
str1=str.split()
l1=0
l2=0
for i in str1:
for j in i:
if j in "eE":
l1=l1+1
elif j in "uU":
l2=l2+1
print("E:", l1)
print("U:", l2)
f.close()
EUCount()
7.
def fun():
f=open("STORY.TXT", "r")
lines=f.readlines()
for i in lines:
if i[-1] in "aeiouAEIOU":
print(i)
f.close()
fun()

8.
def copy():
f=open("FAIPS.TXT", "r")
g=open("DPS.TXT", "a")
str=f.read()
str1=str.split()
for i in str1:
for j in i:
if j.isupper():
f.write(i)
f.close()
g.close()
copy()

9.
import pickle as p
def fun():
f=open("BOOK.DAT", "rb")
No=input("Enter the BookNo to search: ")
while True:
try:
rec=p.load(f)
for i in rec:
if i[0]==No:
print(i)
except:
break
f.close()
fun()

10.
import os
import pickle

#Accepting data for Dictionary


def insertRec():
rollno = int(input('Enter roll number:'))
name = input('Enter Name:')
marks = int(input('Enter Marks'))

#Creating the dictionary


rec = {'Rollno':rollno,'Name':name,'Marks':marks}

#Writing the Dictionary


f = open('d:/student.dat','ab')
pickle.dump(rec,f)
f.close()

#Reading the records


def readRec():
f = open('d:/student.dat','rb')
while True:
try:
rec = pickle.load(f)
print('Roll Num:',rec['Rollno'])
print('Name:',rec['Name'])
print('Marks:',rec['Marks'])
except EOFError:
break
f.close()

#Searching a record based on Rollno


def searchRollNo(r):
f = open('d:/student.dat','rb')
flag = False
while True:
try:
rec = pickle.load(f)
if rec['Rollno'] == r:
print('Roll Num:',rec['Rollno'])
print('Name:',rec['Name'])
print('Marks:',rec['Marks'])
flag = True
except EOFError:
break
if flag == False:
print('No Records found')
f.close()

#Marks Modification for a RollNo


def updateMarks(r,m):
f = open('d:/student.dat','rb')
reclst = []
while True:
try:
rec = pickle.load(f)
reclst.append(rec)
except EOFError:
break
f.close()
for i in range (len(reclst)):
if reclst[i]['Rollno']==r:
reclst[i]['Marks'] = m
f = open('d:/student.dat','wb')
for x in reclst:
pickle.dump(x,f)
f.close()

#Deleting a record based on Rollno


def deleteRec(r):
f = open('d:/student.dat','rb')
reclst = []
while True:
try:
rec = pickle.load(f)
reclst.append(rec)
except EOFError:
break
f.close()
f = open('d:/student.dat','wb')
for x in reclst:
if x['Rollno']==r:
continue
pickle.dump(x,f)
f.close()
while 1==1:
print('Type 1 to insert rec.')
print('Type 2 to display rec.')
print('Type 3 to Search RollNo.')
print('Type 4 to update marks.')
print('Type 5 to delete a Record.')
print('Enter your choice 0 to exit')
choice = int(input('Enter you choice:'))
if choice==0:
break
if choice == 1:
insertRec()
if choice == 2:
readRec()
if choice == 3:
r = int(input('Enter a rollno to search:'))
searchRollNo(r)
if choice == 4:
r = int(input('Enter a rollno:'))
m = int(input('Enter new Marks:'))
updateMarks(r,m)
if choice == 5:
r = int(input('Enter a rollno:'))
deleteRec(r)

11.
import pickle as p
def fun():
f=open("BOOK.DAT", "rb")
No=input("Enter the BookNo to search: ")
while True:
try:
rec=p.load(f)
for i in rec:
if i[0]==No:
print(i)
except:
break
f.close()
fun()

12.
import csv

# To create a CSV File by writing individual lines


def CreateCSV1():
# Open CSV File
Csvfile = open('student.csv', 'w', newline='')
# CSV Object for writing
Csvobj = csv.writer(Csvfile)
while True:
Rno = int(input("Rno:"))
Name = input("Name:")
Marks = float(input("Marks:"))
Line = [Rno, Name, Marks]
# Writing a line in CSV file
Csvobj.writerow(Line)
Ch = input("More(Y/N)?")
if Ch == 'N':
break
Csvfile.close() # Closing a CSV File

# To create a CSV File by writing all lines in one go


def CreateCSV2():
# Open CSV File
Csvfile = open('student.csv', 'w', newline='')
# CSV Object for writing
Csvobj = csv.writer(Csvfile)
Lines = []
while True:
Rno = int(input("Rno:"))
Name = input("Name:")
Marks = float(input("Marks:"))
Lines.append([Rno, Name, Marks])
Ch = input("More(Y/N)?")
if Ch == 'N':
break
# Writing all lines in CSV file
Csvobj.writerows(Lines)
Csvfile.close() # Closing a CSV File

# To read and show the content of a CSV File


def ShowAll():
# Opening CSV File for reading
Csvfile = open('student.csv', 'r', newline='')
# Reading the CSV content in object
Csvobj = csv.reader(Csvfile)
for Line in Csvobj: # Extracting line by line content
print(Line)
Csvfile.close() # Closing a CSV File
print("CSV File Handling")

while True:
Option = input("1:CreateCSV 2:CreateCSVAll 3:ShowCSV
4:Quit ")
if Option == "1":
CreateCSV1()
elif Option == "2":
CreateCSV2()
elif Option == "3":
ShowAll()
else:
break

13.
import csv
al=["id", "password"]
a=[["useridl", "password1"],["userid2",
"password2"],["userid3", "password3"],["userid4",
"password4"],["userid5", "password5"]]
b=input ("Enter username")
myfile=open ("sample.csv", "w+", newline="\n")
myfilel=csv.writer (myfile)
myfilel.writerow(al)
myfilel.writerows (a)
myfile.seek(0)
myfile2=csv.reader (myfile)
for i in myfile2:
if i[0]==b:
print("The paswword is", i[1])
myfile.close()

14.
Stack=[]
List=[0,1,2,4] # Assuming
def PushS(List):
Stack.append(List)
def PopS(List):
if len(Stack) == 0 :
print("Stack is empty!")
else:
print(Stack.pop())

15.
student=[]
list=[[6,"Raju"],[7,"Rohit"]] # Assuming
def push(list):
student.append(list)
def pop(student):
if len(student) == 0 :
print("Stack is empty!")
else:
print(student.pop())
def show(student):
if len(student) == 0 :
print("Stack is empty!")
else:
for i in range(len(student)-1,-1,-1):
print(student[i])

16.
import mysql.connector as con
def createTable():
db=con.connect(host='localhost',user="root",password="",d
atabase="emp")
cur=db.cursor()
cur.execute("create table EMPLOYEE(eno int(5),name
varchar(30),age int(3),salary float(9,2),doj date,address
varchar(30))")
db.commit()
db.close()

def insert():
db=con.connect(host='localhost',user="root",password="",d
atabase="emp")
cur=db.cursor()
eno=int(input("Enter Eno of employee: "))
name=input("Enter Name of employee: ")
age=input("Enter Age of employee: ")
sal=int(input("Enter Salary of employee: "))
doj=input("Enter Date of Joining of employee (YYYY-MM-
DD): ")
address=input("Enter Address of employee: ")
cur.execute("insert into EMPLOYEElues
({},'{}',{},{},'{}','{}')".format(eno,name,age,sal,doj,addr
ess))
db.commit()
db.close()

def display():
db=con.connect(host='localhost',user="root",password="",d
atabase="emp")
cur=db.cursor()
cur.execute("select * from EMPLOYEE")
r=cur.fetchall()
for i in r:
print(i)
print()
db.commit()
db.close()

def update():
db=con.connect(host='localhost',user="root",password="",d
atabase="emp")
cur=db.cursor()
cur.execute("update EMPLOYEE set salary=salary+1000 where
salary<80000")
db.commit()
db.close()

def delete():
db=con.connect(host='localhost',user="root",password="",d
atabase="emp")
cur=db.cursor()
eno=int(input("Enter eno of employee: "))
cur.execute("delete from EMPLOYEE where
eno={}".format(eno))
db.commit()
db.close()
SECTION-B (SQL)

Q1. Consider the tables EMPLOYEE and SALGRADE given below and
answer (a) and (b)parts of this question.

(a) Write SQL commands for the following statements:


(i) To display the details of all EMPLOYEEs in descending order of DOJ
>>select * from employee
order by doj desc;

(ii) To display NAME and DESIG of those EMPLOYEEs whose


SALGRADE is either S02 or S03.
>>select NAME,DESIG from employee
where SGRADE="S03" or SGRADE="S02";

(iii) To display the content of the entire EMPLOYEEs table, whose DOJ
is in between ‘09-Feb-2006’ and ‘08-Aug-2009’.
>>select * from EMPLOYEE
where DOJ between "2006-02-09" and "2009-08-08";

(iv) To add a new row with the following content:


109,‘Harish Roy’,‘HEAD-IT’,‘S02’,‘9-Sep-2007’,‘21-Apr-1983’
>>insert into EMPLOYEE values (109,"Harish Roy","HEADIT","S02",
"2007- 09-09","1983-04-21");
(b) Give the output of the following SQL queries:
(i) SELECT COUNT(SGRADE),SGRADE FROM EMPLOYEE GROUP
BY SGRADE;

COUNT(SGRADE) SGRADE
2 S03
3 S02
1 S01

(ii) SELECT MIN(DOB),MAX(DOJ) FROM EMPLOYEE;

MIN(DOB) MAX(DOB)
1980-01-13 2010-02-10

(iii) SELECT SGRADE, SALARY+HRA FROM SALGRADE WHERE


SGRADE =’S02’;

SGRADE SALARY+HRA
S02 44000

Q2. Study the following table and write SQL queries for questions (i) to
(iv) and output for (v) and (vi).

(i) Write SQL query to display Pname, Quantity and Rate for all the
orders that are either Pencil or Pen.
>>Select pname,quantity,rate from orders
Where pname=”pen or pname=”pencil”;

(ii) Write SQL query to display the orders which are not getting any
Discount.
>>Select * from orders
Where discount is NULL;

(iii) Write SQL query to display the Pname, Quantity and Sale_date for
all the orders whose total cost (Quantity * Rate) is greater than 500.
>>Select pname,quantity, Sale_date from orders
Where Quantity * Rate>500;

(iv) Write SQL query to display the orders whose Rate is in the range
20 to 100.
>>Select * from orders
Where rate between 20 and 100;
(v) SELECT Pname, Quantity from Orders WHERE Pname LIKE(‘_e%’);

Pname Quantity
Pen 10
Pencil 20

(vi) SELECT Pname, Quantity, Rate FROM Orders Order BY Quantity


DESC;
Pname Quantity Rate
Eraser 100 5
Copy 50 20
Pencil 20 10
Book 10 100
Pen 10 20
Q3. Write SQL commands for (i) to (v) on the basis of relations given
below:

(i) To show the books of FIRST PUBL. Publishers written by P. Purohit.


>>Select * from books
Where publishers=”FIRST PUBL.” and author_name=”p.purohit”;

(ii)To display cost of all the books published for FIRST PUBL.
>>Select price from books
Where publishers=”FIRST PUBL.”;
(iii)Depreciate the price of all books of EPB publishers by 5%.
Update books
>>Set price=(price –(price*(5/100)))
Where publishers=”epb”

(iv) To show total cost of books of each type.


>>Select sum(price) from books
Group by type;

(v) To show the details of the costliest book.


>>Select * from books
Where price=max(price);
Q4. Consider the given table and answer the questions.

(i) To show all information of students where capacity is more than the
no. of students in order of rtno.
>>Select * from schoolbus
Where capacity>noofstudents
Order by rtno;

(ii) To show area_covered for buses covering more than 20 km., but
charges less than 80000.
>>Select area_covered from schoolbus
Where distance>20 and charges<80000;

(iii) To show transporter-wise total no. of students travelling.


>>Select sum(noofstudents) “total no of students”
Group by Transporter;

(iv) To show rtno, area_covered and average cost per student for all
routes where average cost per student is—charges/noofstudents.
>>Select rtno, area_covered, charges/noofstudents “average cost”;
(v) Add a new record with the following data:
(11, “Motibagh”,35,32,10, “kisan tours”, 35000)
>>Insert into schoolbus values (11, “Motibagh”,35,32,10, “kisan tours”,
35000);

(vi) Give the output considering the original relation as given:


(a) select sum(distance) from schoolbus where transporter= “Yadav
travels”;
sum(distance)
50

(b)select min(noofstudents) from schoolbus;


min(noofstudents)
40

(c) select avg(charges) from schoolbus where transporter= “Anand


travels”;

avg(charges)
81666.6666667

(d)select distinct transporter from schoolbus;


distinct (transporter)
Shivam travels
Anand travels
Bhalla travels
Yadav travels
Speed travels
Kisan tours
Q5. Given the following tables for a database FURNITURE and
ARRIVAL. Table: FURNITURE
NO ITEMNA TYPE DATEOFSTO PRI DISCOUN
ME CK CE T
1 White Double 23/02/02 300 25
lotus Bed 00
2 Pink Baby 20/01/02 700 20
teather cot 0
3 Dolphin Baby 19/02/02 950 20
cot 0
4 Decent Office 01/01/02 250 30
Table 00
5 Comfort Double 12/01/02 250 25
zone Bed 00
6 Donald Baby 24/02/02 650 15
cot 0
7 Royal Office 20/02/02 180 30
Finish Table 00
8 Royal Sofa 22/02/02 310 30
tiger 00
9 Econo Sofa 13/12/01 950 25
sitting 0
10 Eating Dining 19/02/02 115 25
Paradise Table 00

Table : ARRIVALS
NO ITEMNAME TYPE DATEOFSTOCK PRICE DISCOUNT
11 Wood Double 23/03/03 25000 25
Comfort Bed
12 Old Fox Sofa 20/02/03 17000 20
13 Micky Baby 21/02/03 7500 15
cot

Write SQL commands for the statements (a) to (d)


(a) To list the ITEMNAME which are priced at more than 15000 from
theFURNITURE table.
>>Select itemname from furniture
Where price>15000;
(b) To list ITEMNAME and TYPE of those items, in which
DATEOFSTOCK is before 22/01/02 from the FURNITURE table in
descending order of ITEMNAME.
>>Select Itemname,type from Furniture
Where Dateofstock<”2002-01-22”
Order by Itemname;

(c) To display ITEMNAME and DATEOFSTOCK of those items, in


which the DISCOUNT percentage is less than 25 from FURNITURE
table.
>>Select itemname, dateofstock from furniture
Where discount<25;

(d) To count the number of items, whose TYPE is ‘Sofa’ from


FURNITURE table.
>>Select count(*) from furniture
Where type=”sofa”

You might also like