CS Practical File XII 2023 - 2024 Final
CS Practical File XII 2023 - 2024 Final
Program 1: Input any number from user and calculate factorial of a number
OUTPUT
1
Experiment No:2
Program 2: Input any number from user and check it is Prime number or not.
import math
num = int(input("Enter any number :"))
isPrime=True
for i in range(2,int(math.sqrt(num))+1):
if num % i == 0:
isPrime=False
if isPrime:
print("## Number is Prime ##")
else:
print("## Number is not Prime ##")
OUTPUT
Page : 3
Experiment No: 3
def fib(n):
if n==1:
return 0
elif n==2:
return 1
else:
return fib(n-1) + fib(n-2)
Page : 4
Experiment No: 4
def sum(n,l):
if l==1:
return n[0]
else:
return n[l-1]+sum(n,l-1)
n=eval(input("Enter a list"))
r=sum(n,len(n))
print("The sum is ",r)
Page : 5
Experiment No: 5
Page : 6
Experiment No: 6
def countWord(str1,word):
s = str1.split()
count=0
for w in s:
if w==word:
count+=1
return count
OUTPUT
Enter any sentence :my computer your computer our computer everyones computer
Enter word to search in sentence :computer
## computer occurs 4 times ##
Page : 7
Experiment No: 7
Program 7: Program to read and display file content line by line with each
word separated by „#‟.‟
f = open("file1.txt")
for line in f:
words = line.split()
for w in words:
print(w+'#',end='')
print()
f.close()
OUTPUT
India#is#my#country#
I#love#python#
Python#learning#is#fun#
Page : 8
Experiment No: 8
Program 8: Program to read the content of file and display the total number
of consonants, uppercase, vowels and lower case characters.‟
f = open("file1.txt")
v=0
c=0
u=0
l=0
o=0
data = f.read()
vowels=['a','e','i','o','u']
for ch in data:
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1
if ch.isupper():
u+=1
elif ch.islower():
l+=1
elif ch!=' ' and ch!='\n':
o+=1
print("Total Vowels in filE:",v)
print("Total Consonants in file:",c)
print("Total Capital letters in file:",u)
print("Total Small letters in file:",l)
print("Total Other than letters:",o)
f.close()
NOTE : if the original content of file is:
India is my country
I love python
Python learning is fun
123@
OUTPUT
Total Vowels in file : 16
Total Consonants in file : 30
Total Capital letters in file :2
Total Small letters in file : 44
Total Other than letters :4
Page : 9
Experiment No: 9
Program 9: Program to create binary file to store Rollno and Name, Search
any Rollno and display name if Rollno found otherwise “Rollno not found”
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
student.append([roll,name])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to search :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Search more ?(Y) :")
f.close()
Page : 10
OUTPUT
Enter Roll Number :1
Enter Name :Amit
Add More ?(Y)y
Page : 11
Experiment No: 10
Program 10: Program to create binary file to store Rollno , Name and
Marks and update marks of entered Rollno
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks = int(input("Enter Marks :"))
student.append([roll,name,marks])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb+')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to update :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
print("## Current Marks is :",s[2]," ##")
m = int(input("Enter new marks :"))
s[2]=m
print("## Record Updated ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Update more ?(Y) :")
f.close()
Page : 12
OUTPUT
Enter Roll Number :1
Enter Name :Amit
Enter Marks :99
Add More ?(Y)y
Page : 13
Experiment No: 11
Program 11: Program to read the content of file line by line and write it
to another file except for the lines contains „a‟‟ letter in it.
f1 = open("file2.txt")
f2 = open("file2copy.txt","w")
OUTPUT
Page : 14
Experiment No: 12
import csv
with open('myfile.csv',mode='a') as csvfile:
mywriter = csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee Number "))
name=input("Enter Employee Name ")
salary=int(input("Enter Employee Salary :"))
mywriter.writerow([eno,name,salary])
print("## Data Saved... ##")
ans=input("Add More ?")
ans='y'
with open('myfile.csv',mode='r') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
while ans=='y':
found=False
e = int(input("Enter Employee Number to search :"))
for row in myreader:
if len(row)!=0:
if int(row[0])==e:
print("============================")
print("NAME :",row[1])
print("SALARY :",row[2])
found=True
break
if not found:
print("==========================")
print(" EMPNO NOT FOUND")
print("==========================")
ans = input("Search More ? (Y)")
Page : 15
OUTPUT
Enter Employee Number 1
## Data Saved... ##
Add More ?y
## Data Saved... ##
Add More ? n
============================
NAME : Sunil
SALARY : 80000
============================
==========================
Page : 16
Experiment No: 13
Program 13 Create a CSV file by entering user-id and password , read and
search the password for given user id.
import csv
with open("mail.csv", "w") as obj:
fileobj = csv.writer(obj)
fileobj.writerow(["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the program\n")
if x in "Nn":
break
elif x in "Yy":
continue
with open("mail.csv", "r") as obj2:
fileobj2 = csv.reader(obj2)
given = input("enter the user id to be searched\n")
for i in fileobj2:
next(fileobj2)
# print(i,given)
if i[0] == given:
print(i[1])
break
Page : 17
Experiment No: 14
import random
import time
print("Press CTRL+C to stop the dice ")
play='y'
while play=='y':
try:
while True:
for i in range(10):
print()
n = random.randint(1,6)
print(n,end='')
time.sleep(.00001)
except KeyboardInterrupt:
print("Your Number is :",n)
ans=input("Play More? (Y) :")
if ans.lower()!='y':
play='n'
break
OUTPUT
4Your Number is : 4
Play More? (Y) :y
Your Number is : 3
Play More? (Y) :y
Your Number is : 2
Play More? (Y) :n
Page : 18
Experiment No: 15
def isEmpty(S):
if len(S)==0:
return True
else:
return False
def Push(S,item):
S.append(item)
top=len(S)-1
def Pop(S):
if isEmpty(S):
return "Underflow"
else:
val = S.pop()
if len(S)==0:
top=None
else:
top=len(S)-1
return val
def Peek(S):
if isEmpty(S):
return "Underflow"
else:
top=len(S)-1
return S[top]
def Show(S):
if isEmpty(S):
print("Sorry No items in Stack ")
else:
t = len(S)-1
print("(Top)",end=' ')
while(t>=0):
print(S[t],"<==",end=' ')
t-=1
print()
Page : 19
# main begins here
S=[] #Stack
top=None
while True:
print("**** STACK DEMONSTRATION ******")
print("1. PUSH ")
print("2. POP")
print("3. PEEK")
print("4. SHOW STACK ")
print("0. EXIT")
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Push :"))
Push(S,val)
elif ch==2:
val = Pop(S)
if val=="Underflow":
print("Stack is Empty")
else:
print("\nDeleted Item was :",val)
elif ch==3:
val = Peek(S)
if val=="Underflow":
print("Stack Empty")
else:
print("Top Item :",val)
elif ch==4:
Show(S)
elif ch==0:
print("Bye")
break
OUTPUT
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :10
Continue….
Page : 20
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :20
Page : 22
Experiment No: 16
Program 16: Write a python program to perform to implement a stack for these
book- details(bookno,book name) just implement push and pop operations.
def push(Book):
Bno=int(input("Enter the Book number"))
Bname=input("Enter the Book's Name")
Book.append([Bno,Bname])
def pop(Book):
if Book==[]:
print("underflow")
else:
print("Book Record Deleted",Book.pop())
def display(Book):
if Book==[]:
print("underflow!!!")
else:
print("Books record in Stack\n")
top=len(Book)-1
print(Book[top],"<-top")
for i in range(top-1,-1,-1):
print(Book[i])
Book=[]
while True:
print("\n 1. Push \n 2 Pop \n 3 Display \n 4 Exit")
ch=int(input("Enter your choice"))
if ch==1:
push(Book)
elif ch==2:
pop(Book)
elif ch==3:
display(Book)
else:
break
Page : 23
Experiment No: 17
Program 17: Write a menu driven python program using function Push( ) , Pop and
Display to implement the stack . The program will store the Employee
details i.e. Employee number , Employee name and salary.
def push(Emp):
eno=int(input("Enter the Employee number"))
ename=input("Enter the Employee Name")
sal=float(input("Enter the salary"))
Emp.append([eno,ename,sal])
def pop(Emp):
if Emp==[]:
print("underflow")
else:
print("Employee Record Deleted",Emp.pop())
def display(Emo):
if Emp==[]:
print("underflow!!!")
else:
print("Employee record in Stack\n")
top=len(Emp)-1
print(Emp[top],"<-top")
for i in range(top-1,-1,-1):
print(Emp[i])
Emp=[]
while True:
print("\n 1. Push \n 2 Pop \n 3 Display \n 4 Exit")
ch=int(input("Enter your choice"))
if ch==1:
push(Emp)
elif ch==2:
pop(Emp)
elif ch==3:
display(Emp)
else:
break
Page : 24
Experiment No: 18
Page : 25
OUTPUT
0. ADD RECORD
1. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :1
Enter Name :AMIT
Enter Department :SALES
Enter Salary :9000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :2
Enter Name :NITIN
Enter Department :IT
Enter Salary :80000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :2
EMPNO NAME DEPARTMENT SALARY
1 AMIT SALES 9000
2 NITIN IT 80000
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :0
## Bye!! ##
Page : 26
Experiment No: 19
Program 19: Program to connect with database and search employee number
in table employee and display record, if empno not found display
appropriate message.
OUTPUT
########################################
EMPLOYEE SEARCHING FORM
########################################
Page : 27
Experiment No: 20
Page : 28
OUTPUT
########################################
EMPLOYEE UPDATION FORM
########################################
Page : 29
Experiment No: 21
Program 21: Program to connect with database and delete the record
of entered employee number.
Page 30
E Experiment No: 22
Program 22: Program to connect with database and store record 0f student and
display records.
Program 23: Program to connect with database and search student number in
table student and display record, if sturno not found display appropriate
message.
import mysql.connector as mycon
con=mycon.connect(host="localhost",user="root",password="qmgs",database="school")
cur=con.cursor()
print("#"*40)
print("Student searching form")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
sturno=int(input("Enter Student Roll number to search:"))
query="select*from student where sturno={}".format(sturno)
cur.execute(query)
result=cur.fetchall()
if cur.rowcount==0:
print("Sorry!student not found")
else:
print("%10s"%"StudentRollnumber","%20s"%"Name","%15s"%"subject","%10s"%"marks")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
ans=input("Search more(Y):")
Page 32
Experiment No: 24
Program 24: Program to connect with database and update the student
record of entered sturno.
Program 25: Program to connect with database and delete the record of
entered employee number.
Page 34
Q26. Consider the following table named STUDENT. Write command of MySQL for (i) to (viii) and output for
(ix) and (x).
Table : STUDENT
Adno SName Marks Clsection Stream
R001 Sushant 90.2 12A Science
R002 Vaidyanath 80.5 12B Humanities
R003 Miara 68.9 12B Science
R004 Niara 96.0 12A Commerce
R005 Shinjini 88.9 12D Commerce
(i) To display all information of the students of humanities in descending order of percentage.
(ii) To display Adno, Name, Marks and Stream of those students whose name is less than 6 characters
long.
Ans. select adno, sname, marks, stream from student where length(sname) < 6;
(iii) To find the min, max, sum, and average of the marks
(vi) To add another column Bus_Fees with datatype and size as Decimal (8,2).
(ix) SELECT SName, Marks FROM STUDENT WHERE Name LIKE "N%";
Ans.
SName Marks
Niara 9 6.0
Page 35
Q27. Consider the following table ‘Transporter’ that stores the order details about items to be transported.
Write SQL commands for the statements (i) to (viii) and write output for SQL queries (ix) and (x).
(i) To display names of drivers and destination city where TELEVISION is being transported.
(ii) To display driver names and destinations where destination is not MUMBAI.
(iii) To display the names of destination cities where items are being transported. There should be no
duplicate values.
(iv) To display details of rows that have some value in DRIVERGRADE column.
Ans. select drivername, item, traveldate from transporter where traveldate<= '2019-04-01';
(vi) To display the number of drivers who have ‘MOHAN’ anywhere in their names.
(vii) To display the names of drivers, item names and travel dates in alphabetic (ascending) order of driver
names.
Page 36
(viii) To display names of drivers whose names are three characters long
(ix) SELECT ITEM, COUNT(*) FROM TRANSPORTER GROUP BY ITEM HAVING COUNT(*) >1;
Ans.
ITEM COUNT(*)
TELEVISION 3 3
REFRIGERATOR 2 2
Ans.
MAX(TRAVELDATE)
2019-04-19
Page 37
Continue….
Q 28. Consider the following table ‘Furniture’. Write SQL commands for the statements (i) to (viii) and write
output for SQL queries (ix) and (x).
(i) To display FCODE, NAME and PRICE of items that have Price less than < 5000.
(ii) To display NAMES and PRICE of those Furniture Items that have ‘table’ anywhere in their names.
Ans. select name, price from furniture where name like '%table%';
(iv) To display the NAMES and PRICE increased by 500.00 of all the furniture items. (Price should only
be displayed as increased; there should be no increase in the data in the table)
(v) To display FCODE and NAME of each Furniture Item in descending order of FCODE.
(vi) To display the details of all the Furniture Items which have Manufacturing date (MANUFDATE)
between 01-JAN-2016 and 15-JUN-2017 (inclusive of both the dates).
Ans. select * from furniture where manufdate between '2016-01-01' and '2017-06-15';
(vii) To display the average PRICE of all the Furniture Items, which are made of Wood with WCODE as
W02.
Page 38
(viii) To display WCODE wise, WCODE and the highest price of Furniture Items.
Ans.
SUM(PRICE)
6500
Ans.
W CODE MAX(PRICE)
W03 4000
W01 20500
W02 35000
Page 39
Continue…..
Q29. Consider the following tables PARTICIPANT and ACTIVITY and answer the questions that follow :
With reference to the above given tables, write commands in SQL for (i) to (iii).
(i) To display Activity Code along with number of participants participating in each activity (Activity
Code wise) from the table Participant.
(ii) To display Names of Participants, Activity Code, Activity Name in alphabetic ascending order of
names of participants.
Ans. select name, A.activitycode, activityname from participant A, activity B where A.activitycode = B.activitycode
order by name ;
(iii) To display Names of Participants along with Activity Codes and Activity Names for only those
participants who are taking part in Activities that have ‘bag’ in their Activity Names and Points of
activity are above 250.
Ans. select name, A.activitycode, activityname from participant A, activity B where A.activitycode = B.activitycode
and activityname like '%bag%' and points>250;
Page 40
Continue…..
Q. 30 Create a database “Pract2022” and make table “Worker” and “Dept” as per the details given
below:-
Table: WORKER
WID WNAME JOB SALARY DNO
1001 KANAK JAIN CLERK 15000 D03
1002 MUKESH VYAS ELECTRICIAN 11000 D01
1003 SURESH FITTER 9000 D02
1004 ANKUR GUARD 8000 D01
1005 RAM CLERK 14000 D03
Table: DEPT
DNO DNAME LOCATION MANAGER
D01 PRODUCTION GROUND FLOOR SHREYA
D02 ACCOUNTS 1ST FLOOR PRANSHU
D03 SALARY 1ST FLOOR KHUSHI
Q. 1 Display Worker ID, WName and Job who are working under SHREYA
Ans Select WID , WName , Job
From Worker , Dept
Where Worker.Dno = Dept.Dno and Manager = “Shreya”;
Q. 2 Display Worker name and their respective department names who are working as ELCTRICIAN.
Ans. Select WName , DName
From Worker , Dept
Where Worker.Dno = Dept.Dno and Job=”Electrician”;
8000
Page 41