practical file cs
practical file cs
Practical File
Class: XII G
Roll no.: 48
CERTIFICATE
This is to certify that I smriti joshi of Class XII G PM
shri Kendriya Vidyalaya Noida , have successfully completed 25
Practicals out of 25 Practicals in computer science for the
AISSCE as prescribed by CBSE .
Date :
__________________ __________________
PRINCIPAL
Index
Aim Date Sign
Page | 2
binary file student.dat.
Page | 3
operation on stack in python
using list.
18 Write a menu based program to 03.09.2024
perform PUSH, POP and DISPLAY
operation on stack in python
using Dictionary.
19 Write a program to connect 11.09.2024
Python with MySQL using
database connectivity and
perform the following operations
on data in
database:company(Table:employe
e) Add, Search, Update, Delete
and View complete Table.
Page | 4
24 Consider following tables and answer 16.10.2024
queries (i) to (iv): -
Page | 5
1. Write a program in python to check a number whether it is Prime or not using
user defined function.
def prime(f):
i=2
while i<=f-1:
if f%i==0:
break
i=i+1
if f==i:
print("Prime")
else:
print ("Not Prime")
a=int (input ("Enter the number"))
prime(a)
Page | 6
2. Write a program to input a character and to print whether a given character is an
alphabet, digit or any other character.
ch=input ("Enter a character: ")
if ch.isalpha():
print(ch, "is an alphabet")
elif ch.isdigit():
print(ch, "is a digit")
elif ch.isalnum():
print(ch, "is alphabet and numeric")
else:
print(ch, "is a special symbol")
Page | 7
3. Write a python function sin(x,n) to calculate the value of sin(x) using its Taylor
series expansion up to n terms.
import math
def fact(k):
if k<=1:
return 1
else:
return k*fact(k-1)
Page | 8
4. Write a program to generate random numbers between 1 to 6 and check
whether a user won a lottery or not.
import random
n=random.randint(1,6)
guess=int(input("Enter a number between 1 to 6 :"))
if n==guess:
print("Congratulations, You won the lottery ")
else:
print("Sorry, Try again, The lucky number was : ", n)
Page | 9
5. Write a program to count the number of vowels present in a text file.
count=0
ch='y'
f=open('test.txt','w')
while ch=='y':
line=input("Enter line:")
f.write(line)
f.write('\n')
ch=input("More lines?")
f.close()
f=open('test.txt','r')
for f1 in f.read():
if f1=='a'or f1=='e'or f1=='i'or f1=='o‘ or f1=='u':
count=count+1
print(count)
f.close()
Page | 10
6. Write a program to write those lines which have the character 'p' from one text
file to another text file.
fin=open("E:\\book.txt","r")
fout=open("E:\\story.txt","a")
s=fin.readlines()
for j in s:
if 'p' in j:
fout.write(j)
fin.close()
fout.close()
7. Write a program to count number of words in a Text file.
count=0
ch='y'
f=open('test.txt','w')
while ch=='y':
line=input("Enter line:")
f.write(line)
f.write('\n')
ch=input("More lines?")
f.close()
f=open('test.txt','r')
for word in f.read().split():
count=count+1
print(count)
f.close()
Page | 11
8. Write a program to insert n records in a binary file student.dat.
import pickle
ch='y'
f = open('d:/student.dat','wb')
while ch=='y':
rollno = int(input('Enter roll number:'))
name = input('Enter Name:')
marks = int(input('Enter Marks'))
rec = {'Rollno':rollno,'Name':name,'Marks':marks}
pickle.dump(rec,f)
ch=input("more entry?")
f.close()
Page | 12
9. Write a program to read records from binary file student.dat.
import pickle
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()
Page | 13
10. Write a program to implement search operation in a binary file.
import pickle
f = open('d:/student.dat','rb')
flag = False
r=int(input("Enter rollno to be searched"))
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()
Page | 14
11. Write a program to update a record stored in binary file student.dat.
import pickle
f = open('d:/student.dat','rb')
reclst = []
r=int(input("enter roll no to be updated"))
m=int(input("enter correct marks"))
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()
Page | 15
12. Write a program to delete a record from binary file.
import pickle
f = open('d:/student.dat','rb')
reclst = []
r=int(input("enter roll no to be deleted"))
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()
Page | 16
13. Write a program to create a CSV file and read it.
import csv
with open('d:\\myfile.csv') as csvfile:
myreader=csv.reader(csvfile,delimiter=',')
print("%10s"%"EMPNO","%20s"%"EMP Name""%10s"%"Salary")
print(" ")
for row in myreader:
if len(row)!=0:
print("%10s"%row[0],"%15s"%row[1],"%10s"%row[2])
Note:
1. Create a notepad file myfile.csv in d:\. Write data for
file with comma separated.
2. Go to Tools->Folder Option->view->uncheck hide
extension for unknown file types
3. Rename myfile.csv.txt -> myfiel.csv
Page | 17
14. Write a program to count umber of records from CSV file.
import csv
with open('d:\\myfile.csv') as csvfile:
myreader=csv.reader(csvfile,delimiter=',')
count=0
print("%10s"%"EMPNO","%20s"%"EMP
Name""%10s"%"Salary")
print(" ")
for row in myreader:
if len(row)!=0:
print("%10s"%row[0],"%20s"%row[1],"%10s"%row[2])
count=count+1
print(" ")
print("%30s"% "Total Records are:", count)
print(" ")
Page | 18
15. Write a program to save some user id and passwords in a csv file. Ask user to
enter a user id and password, if combination matches it should print ‘welcome’
other wise print ‘data mismatch’.
import csv
newFile=open('d:\\a.csv','w')
nfw = csv.writer(newFile)
#nfw.writerow(['user_id','password'])
ch='y'
while ch=='y':
userid=input("enter userid")
password=input("Enter password")
nfw.writerow([userid,password])
ch=input("More entry?(y/n)")
newFile.close()
newFile.close()
newFile=open('d:\\a.csv','r')
newFileReader = csv.reader(newFile)
flag=False
userid=input("enter userid")
password=input("Enter password")
for row in newFileReader:
if len(row)!=0:
if row[0]==userid and row[1]==password:
print('Welcome')
flag=True
break
if flag==False:
print(‘Either username or Password is incorrect')
Page | 19
16. Write a program to insert an element in the list.
def findpos(ar,item):
size=len(ar)
if item<ar[0]:
return 0
else:
pos=-1
for i in range(size-1):
if(ar[i]<=item and item<ar[i+1]):
pos=i+1
break
if(pos==-1 and i<=size):
pos=size
return pos
def shift(ar,pos):
ar.append(None) # add an empty element at the end
size=len(ar)
i=size-1
while i>=pos:
ar[i]=ar[i-1]
i=i-1
list=[10,20,30,40,50,60,70]
print("list in sorted order is")
print(list)
item=int(input("Enter element to be inserted:"))
position=findpos(list,item)
shift(list,position)
list[position]=item
print("The list after insertion is:",item,"is")
print(list)
Page | 20
17. Write a menu based program to perform PUSH, POP and
DISPLAY operation on stack in python using list.
s=[]
def push(a):
s.append(a)
def pop():
if(s==[]):
print("Stack Empty")
else:
print("Element Deleted is :",s.pop())
def display():
l=len(s)
for i in range(l-1,-1,-1):
print(s[i])
c="y"
while(c=="y"):
print("1. PUSH")
print("2. POP")
print("3. DISPLAY")
choice=int(input("Enter your choice"))
if(choice==1):
a=input("Enter any number: ")
push(a)
elif (choice==2):
pop()
elif(choice==3):
display()
else:
print("Wrong Input")
c=input("Do you want to continue?")
Page | 21
Page | 22
18. Write a menu based program to perform PUSH, POP and
DISPLAY operation on stack in python using Dictionary.
score={'anuj':40,'sachin':55,'saurav':80,'raj':35,'ajay':42}
def PUSH():
k=input('Enter Key')
val=int(input('Enter Value'))
s={k:val}
score.update(s)
def POP():
L=list(score.keys())
print('Popped Value is:')
print('Key=',L[-1])
print('value=',score.pop(L[-1]))
def DISPLAY():
temp = dict(reversed(list(score.items())))
print("The reversed order dictionary ", temp)
c='y'
while(c=="y"):
print("1. PUSH")
print("2. POP")
print("3. DISPLAY")
choice=int(input("Enter your choice"))
if(choice==1):
PUSH()
elif (choice==2):
POP()
elif(choice==3):
DISPLAY()
else:
print("Wrong Choice")
c=input("Do you want to continue?")
Page | 23
Page | 24
19. Write a program to connect Python with MySQL using
database connectivity and perform the following operations on data
in database:company(Table:employee) Add, Search, Update, Delete
and View complete Table.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="employee")
mycursor=mydb.cursor()
def employeeadd():
L=[]
eno=int(input("Enter eno:"))
L.append(eno)
ename=input("Enter ename:")
L.append(ename)
esalary=int(input("Enter esalary:"))
L.append(esalary)
value=L
value=(eno,ename,esalary)
sql="insert into
employee(eno,ename,esalary)values(%s,%s,%s)"
mycursor.execute(sql,value)
mydb.commit()
def employeesearch():
en=int(input("Enter eno to search"))
rl=(en,)
sql="select * from employee where eno=%s"
mycursor.execute(sql,rl)
res=mycursor.fetchall()
print("Details are as follows:")
print("(eno,ename,esalary)")
for x in res:
print(x)
def employeedelete():
e=int(input("Enter the eno to delete:"))
rl=(e,)
Page | 25
sql="delete from employee where eno=%s"
mycursor.execute(sql,rl)
mydb.commit()
def employeeupdate():
e=int(input("Enter the eno to update:"))
sqll=("select * from employee where eno=%s")
rl=(e,)
value=int(input("Enter the amount to be added:"))
sql=("update employee set esalary=esalary+%s where
eno=%s")
data=(value,e)
mycursor.execute(sql,data)
mydb.commit()
def employeeview():
sql="select * from employee"
mycursor.execute(sql)
res=mycursor.fetchall()
print("(eno,ename,esalary)")
for x in res:
print(x)
def menu():
print("*************************")
print("Press 1- To add data")
print("Press 2- To search record")
print("Press 3- To delete record")
print("Press 4- To Update record")
print("Press 5- to View complete Table")
print("*************************")
userinput=int(input("Please select an option from
above"))
if(userinput==1):
employeeadd()
elif(userinput==2):
employeesearch()
elif(userinput==3):
employeedelete()
Page | 26
elif(userinput==4):
employeeupdate()
elif(userinput==5):
employeeview()
else:
print("Wrong Choice")
def runagain():
again=input("\Want to run again y/n?")
while(again=='y'):
menu()
again=input("\nWant to run again y/n?")
menu()
runagain()
print("Thanks for using Program")
Page | 27
OUTPUT
Page | 28
Page | 29
20. Write a program to connect Python with MySQL using
database connectivity and perform the following operations on data
in database:Class_management(Table:Class_info) Fetch, Update
and delete the data.
import mysql.connector
import datetime
mydb=mysql.connector.connect(host="localhost",\
user="root",\
passwd="root",\
database="Class_management")
mycursor=mydb.cursor()
def testadd():
L=[]
Rno=int(input("Enter Roll no:-"))
L.append(Rno)
Sname=input("Enter Student's name:-")
L.append(Sname)
Class=int(input("Enter Class:-"))
L.append(Class)
Dob=input("Enter DOB:-")
L.append(Dob)
Fees=float(input("Enter Fees :-"))
L.append(Fees)
Address=input("Enter Student's Address:-")
L.append(Address)
Phone_no=int(input("Enter Phone no:-"))
L.append(Phone_no)
Fname=input("Enter Father's name:-")
L.append(Fname)
Mname=input("Enter Mother's name:-")
L.append(Mname)
Sub=input("Enter Student's Subjects:-")
L.append(Sub)
value=L
Page | 30
value=(Rno,Sname,Class,Dob,Fees,Address,Phone_no,Fname,Mname,Sub)
sql="insert into
class_info(Rno,Sname,Class,Dob,Fees,Address,Phone_no,Fname,Mna
me,Sub)values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
mycursor.execute(sql,value)
mydb.commit()
def testsearch():
rn=int(input("Enter Roll no. to search:-"))
rl=(rn,)
sql="select * from class_info where Rno=%s"
mycursor.execute(sql,rl)
res=mycursor.fetchall()
print("Details are as follows:")
print("(Rno,Sname,Class,Dob,Fees,Address,Phone_no,Fname,Mname,Sub)"
)
for x in res:
print(x)
def testdelete():
r=int(input("Enter the Roll no. to delete:-"))
rl=(r,)
sql="delete from class_info where Rno=%s"
mycursor.execute(sql,rl)
mydb.commit()
def testupdate():
rr=int(input("Enter the Roll no. to update:-"))
sqll=("select * from class_info where Rno=%s")
rl=(rr,)
value=int(input("Enter the Roll no to update:-"))
rll=(value,)
Page | 31
sql=("update class_info set Fees=Fees+%s where Fees=%s")
data=(value1,e)
mycursor.execute(sql,data)
mydb.commit()
ra=int(input("Enter the Roll no. to update:-"))
sqll=("select * from class_info where Rno=%s")
rl=(ra,)
value2=input("Enter the Address to update:-")
rll=(value2,)
else:
print("Wrong Choice")
Page | 32
#now=datetime.datetime.now()
def menu():
print("************************************** ")
print("* Press 1- To Add Entry * ")
print("* Press 2- To Search record * ")
print("* Press 3- To Delete record * ")
print("* Press 4- To Update record * ")
print("************************************** ")
userinput=int(input("Please select an option from above"))
if(userinput==1):
testadd()
elif(userinput==2):
testsearch()
elif(userinput==3):
testdelete()
elif(userinput==4):
testupdate()
else:
print("Wrong Choice")
def runagain():
again=input("\Want to run again y/n?")
while(again=='y'):
menu()
again=input("\nWant to run again y/n?")
menu()
runagain()
print("Thanks for using Program")
Page | 33
Page | 34
21. Create the following table PRODUCT in MySql and answer the
questions follows:
TABLE : PRODUCT
Page | 35
ii. To display average price of product sorted on the basis of
Manufacturer.
select Manufacturer, avg(price) from PRODUCT group by
Manufacturer;
Page | 36
v. To display product name and price of product having P_ID
either BS01 or FW12.
select ProductName,Price from product where P_ID
in('BS01','FW12');
Page | 37
viii. To print average Price of product from manufacturer either
‘ABC’ or ‘XYZ’.
select avg(price) from PRODUCT where Manufacturer in
(‘ABC’,’XYZ’);
Page | 38
22. Consider following tables and answer queries (i) to (iv)
SUPPLIER
SNO SNAME CITY
1 ABC Pvt NEW DELHI
2 INDIA Enterprises JAIPUR
3 Deep Ltd UDAIPUR
4 G&G Corp JAIPUR
ITEM
CODE I_NAME PRICE SNO
C1 COLD DRINK 150 2
B2 BISCUITS 100 3
T3 TEA 200 1
a) Display Item code and item name whose price is more than 100 in the
descending order of price.
c) Display Supplier no, supplier name who have supplied item for which item code
is B2.
d) List the Item name, price, and supplier name of item(s) which have been supplied
by a supplier
of JAIPUR.
Page | 39
23. Consider following tables and answer queries (a) to (c) and write down
the output of (d) : -
CUSTOMER
Cust_I CNAME GENDE CITY CLUB_I
D R D
C01 DEVESH M NEW 101
DELHI
C02 SURAJ M JAIPUR 102
C03 SHEELA F UDAIPUR 102
C04 MEENAKS F JAIPUR 101
HI
C04 AAKRITI F UDAIPUR 103
CLUB
CLUB_ID CLUB_NAME FEES
101 YOGA 800
102 MUSIC 1000
103 SPORTS 2000
c) SELECT CNAME,GENDER,CLUB_NAME
FROM CUSTOMER,CLUB
DEVESH YOGA
SURAJ MUSIC
Page | 40
24. Consider following tables and answer queries (i) to (iv): -
WORKER
WID WNAME JOB SALARY DNO
1001 RAHUL CLERK 15000 D03
SHARMA
1002 MUKESH ELECTRICIAN 11000 D01
VYAS
1003 SURESH FITTER 9000 D02
1004 ANKUR GUARD 8000 D01
DEPT
DNO DNAME LOCATION MANAGER
D01 PRODUCTION GROUND FLOOR D K JAIN
D02 ACCOUNTS 1ST FLOOR S ARORA
D03 SECURITY 1ST FLOOR R K SINGH
a) How many departments are there on the first floor?
b) Display Worker name and their respective jobs whose name contains the string
‘ESH’.
c) Display the average salary of workers who are working in the “PRODUCTION”
department.
d) Display Worker name, Job and their respective manager.
Page | 41
25. Write queries (a) to (d) based on the tables CUSTOMER and ORDER
given below:
TABLE:CUSTOMER
CUSTOMERID CUSTOMERNAME CITY COUNTRY
101 AMAN JAIPUR INDIA
102 SURESH BARANG GERMANY
103 ANAND RODIX MEXICO
104 RISHABH TENDA GERMANY
105 AARYAN KOTA INDIA
TABLE:ORDER
ORDERID CUSTOMERID ORDERDATE
1 101 12/5/2016
2 102 3/8/1990
3 101 21/9/2020
(a) To display customer name with their order id.
(b) To display the total number of customers country-wise.
(c) To display customer names in ascending order who have placed orders.
(d) To display the total number of customers whose city name starts with “J”.
(a)
SELECT CUSTOMERNAME,ORDERID FROM CUSTOMER,ORDER
WHERE CUSTOMER.CUSTOMERID=ORDER.CUSTOMERID;
(b)
SELECT COUNTRY,COUNT(*) FROM CUSTOMER
GROUP BY COUNTRY;
(c)
SELECT CUSTOMERNAME FROM CUSTOMER,ORDER
WHERE CUSTOMER.CUSTOMERID=ORDER.CUSTOMERID
ORDER BY CUSTOMERNAME;
(d)
SELECT COUNT(*)
FROM CUSTOMER
WHERE CITY LIKE ”J%”;
*********************************************
Page | 42