Practical File Computer Science - 24 - 25
Practical File Computer Science - 24 - 25
COMPUTER SCIENCE
PRACTICAL FILE (2024-25)
INDEX
Exp.
No Aim Date Sign
Program to read and display file content line by 05/07/2024
1 line with each word separated by “ #”
Program to read the content of file and display 12/07/2024
2 the total number of consonants, uppercase,
vowels and lowercase characters.
Program to read the content of file line by line 19/07/2024
3 and write it to another file except for the lines
contains “a” letter in it.
Program to store students’ details like admission 26/07/2024
number, roll number, name and percentage in a
4
dictionary and display information on the basis of
admission number.
Program to create binary file to store Roll no and 02/08/2024
5 Name, Search any Roll no and display name if Roll no
found otherwise “Roll no not found”
Program to create binary file to store Roll no, Name 09/08/2024
6
and Marks and update marks of entered Roll no.
Program to generate random number 1-6, simulating a 16/08/2024
7
dice.
8 Program to implement Stack in Python using List. 23/08/2024
Create a CSV file by entering user-id and password, 30/08/2024
9 read and search the password for given user- id.
To write SQL-Queries for the following Questions 06/09/2024
10
based on the given table
To write SQL-Queries for the following Questions 13/09/2024
11
based on the given table
To write Queries for the following Questions based on 20/09/2024
12
the given two table
Program to connect with database and store record of 04/10/2024
13
employee and display records.
Program to connect with database and search 18/10/2024
employee number in table employee and display
14
record, if empno not found display appropriate
Message
Perform all the operations (Insert, Update, Delete, 25/10/2024
15 Display) with reference to table ‘students’ through
MySQL-Python connectivity
Program 1
Objective: Write a 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()
India is my country
I love python
Python learning is fun
OUTPUT
India#is#my# country#
I#love#python#
Python#learning#is#fun#
>>>
Program 2
Objective: W r i t e a p rogram 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()
OUTPUT
Total Vowels in file : 16
Total Consonants in file : 30
Total Capital letters in file : 3
Total Small letters in file : 43
Total Other than letters : 0
>>>
Program 3
Objective: Write a 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("file1.txt")
f2 = open("file2.txt","w") for
line in f1:
if 'a' not in line:
f2.write(line)
print("## File Copied Successfully! ##")
f1.close()
f2.close()
India is my country
I love python
Python learning is fun
OUTPUT
## File Copied Successfully! ##
>>>
Program 4
Objective: Write a program to store student’s details like admission number, roll number, name and
percentage in a dictionary and display information on the basis of admission number.
record = dict ()
i=1
n= int (input ("How many records u want to enter: "))
while(i<=n):
Adm = input("Enter Admission number: ")
roll = input("Enter Roll Number: ")
name = input("Enter Name :")
perc = float(input("Enter Percentage : "))
t = (roll,name, perc)
record[Adm] = t
i=i+1
Nkey = record.keys()
for i in Nkey:
print("\nAdmno- ", i, " :")
r = record[i]
print("Roll No\t", "Name\t", "Percentage\t")
for j in r:
print(j, end = "\t")
OUTPUT
Admno- 101 :
Roll No Name Percentage
38 Ramesh 78.0
Admno- 102 :
Roll No Name Percentage
39 Mahesh 79.0
>>>
Program 5
Objective: Write a program to create binary file to store Roll no and Name, Search any Roll no and display
name if Roll no found otherwise “Roll no not found”
import pickle
D={}
f=open("Studentdetails.dat","wb")
def write():
while True:
rno = int(input("Enter Roll no : "))
n = input("Enter Name : ")
D['Roll_No']=rno
D['Name'] = n
pickle.dump(D,f)
ch = input("More ? (Y/N)")
if ch in 'Nn':
f.close()
break
def Search() :
found = 0
rollno= int(input("Enter Roll no Whose name you want to display :"))
f = open("Studentdetails.dat", "rb")
try:
while True:
rec = pickle.load(f)
if rec['Roll_No']==rollno:
print(rec['Name'])
found = 1
break
except EOFError:
if found == 0:
print("Sorry not Found. .. ")
f.close()
write()
Search()
OUTPUT
Enter Roll no : 1
Enter Name : Ramesh
More ? (Y/N)y
Enter Roll no : 2
Enter Name : Mahesh
More ? (Y/N)y
Enter Roll no Whose name you want todisplay :2
Mahesh
Program 6
Objective: Write a program to create binary file to store Roll no, Name and Marks and update marks of
entered Roll no.
import pickle
def Write():
f = open("Studentdetails.dat", 'wb')
while True:
r =int(input ("Enter Roll no : "))
n = input("Enter Name : ")
m = int(input ("Enter Marks : "))
record = [r,n,m]
pickle.dump(record, f)
ch = input("Do you want to enter more ?(Y/N)")
if ch in 'Nn':
break
f.close()
def Read():
f = open("Studentdetails.dat",'rb')
try:
while True:
rec=pickle.load(f)
print(rec)
except EOFError:
f.close()
def Update():
f = open("Studentdetails.dat", 'rb+')
rollno = int(input("Enter roll no whoes marks you want to update"))
try:
while True:
pos=f.tell()
rec = pickle.load(f)
if rec[0]==rollno:
um = int(input("Enter Update Marks:"))
rec[2]=um
f.seek(pos)
pickle.dump(rec,f)
print(rec)
except EOFError:
f.close()
Write()
Read()
Update()
Read()
OUTPUT
Enter Roll no : 1
Enter Name : ramesh
Enter Marks : 78
Do you want to enter more ?(Y/N)N
[1, 'ramesh', 78]
Enter roll no whoes marks you want to update1
Enter Update Marks:87
[1, 'ramesh', 87]
>>>
Program 7
Objective: Write a program to generate random number 1-6, simulating a dice.
import random
while True:
print("="*55)
print("***********************Roling Dice****************************")
print("="*55)
num = random.randint(1,6)
if num ==6:
print("Hey.....You got",num,". ...... Congratulations!!!!")
elif num ==1:
print("Well tried. ... But you got",num)
else:
print("You got:",num)
ch=input("Roll again? (Y/N)")
if ch in "Nn":
break
print("Thank for playing!!!!!!!!")
OUTPUT
=======================================================
***********************Roling Dice****************************
=======================================================
You got: 2
Roll again? (Y/N)y Thank for
playing!!!!!!!!
=======================================================
***********************Roling Dice****************************
=======================================================
Hey.....You got 6....... Congratulations!!!!
Program 8
Objective: Write a program to implement Stack in Python using List.
employee=[]
def push():
empno=input("Enter empno ")
name=input("Enter name ")
sal=input("Enter sal ")
emp=(empno,name,sal)
employee.append(emp)
def pop():
if(employee==[]):
print("Underflow / Employee Stack in empty")
else:
empno,name,sal=employee.pop()
print("poped element is ")
print("empno ",empno," name ",name," salary ",sal)
def traverse():
if not (employee==[]):
n=len(employee)
for i in range(n-1,-1,-1):
print(employee[i])
else:
print("Empty , No employee to display")
while True:
print("1. Push")
print("2. Pop")
print("3. Traversal")
print("4. Exit")
ch=int(input("Enter your choice "))
if(ch==1):
push()
elif(ch==2):
pop()
elif(ch==3):
traverse()
elif(ch==4):
print("End")
break
else:
print("Invalid choice")
OUTPUT
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 1
Enter empno 101
Enter name Ramesh
Enter sal 34000
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 3
('101', 'Ramesh', '34000')
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice
Program 9
Objective: Create a CSV file by entering user-id and password, read and search the password for given
user- id.
import csv
with open("user_info.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("user_info.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
OUTPUT
(e) Write a Query to List all the tables that exists in the current database.
Sol:
mysql> SHOW TABLES;
Output:
(f) Write a Query to insert all the rows of above table into Info table.
Sol:
INSERT INTO STU VALUES (1,'Arun','M', 24,'COMPUTER','1997-01-10', 120);INSERT
INTO STU VALUES (2,'Ankit','M', 21,'HISTORY','1998-03-24', 200);
INSERT INTO STU VALUES (3,'Anu','F', 20,'HINDI','1996-12-12', 300);
INSERT INTO STU VALUES (4,'Bala','M', 19, NULL,'1999-07-01', 400);
INSERT INTO STU VALUES (5,'Charan','M', 18,'HINDI','1997-06-27', 250);
INSERT INTO STU VALUES (6,'Deepa','F', 19,'HISTORY','1997-06-27', 300);
INSERT INTO STU VALUES (7,'Dinesh','M', 22,'COMPUTER','1997-02-25', 210);
INSERT INTO STU VALUES (8,'Usha','F', 23, NULL,'1997-07-31', 200);
(g) Write a Query to display all the details of the Employees from the above table 'STU'.
Sol:
Output:
(h) Write a query to Rollno, Name and Department of the students from STU
table.
Sol:
mysql> SELECT ROLLNO,NAME,DEPT FROM STU;
Program 11
Objective: To write SQL- Queries for the following Questions based on the given
table:
(b) Write a Query to change the fess of Student to 170 whose Roll number is 1, if the existing
fessis less than 130.
Sol:
Output(After Update):
(c) Write a Query to add a new column Area of type varchar in table STU.
Sol:
mysql> ALTER TABLE STU ADD AREA VARCHAR(20);
Output:
(d) Write a Query to Display Name of all students whose Area Contains NULL.
Sol:
mysql> SELECT NAME FROM STU WHERE AREA IS NULL;
Output:
(e) Write a Query to delete Area Column from the table STU.
Sol:
mysql> ALTER TABLE STU DROP AREA;
Output:
Objective: To write Queries for the following Questions based on the given two table.
TABLE: STOCK
Pno Pname Dcode Qty UnitPrice StockDate
5005 Ball point pen 102 100 10 2021-03-31
5003 Gel pen premium 102 150 15 2021-01-01
5002 Pencil 101 125 4 2021-02-18
5006 Scale 101 200 6 2020-01-01
5001 Eraser 102 210 3 2020-03-19
5004 Sharpner 102 60 5 2020-12-09
5009 Gel pen classic 103 160 8 2022-01-19
TABLE: DEALERS
Dcode Dname
101 Sakthi Stationeries
103 Classic Stationeries
102 Indian Book House
(a) To display the total Unit price of all the products whose Dcode as 102.
Sol:
mysql> SELECT SUM(UNITPRICE) FROM STOCK GROUP BY DCODE
HAVINGDCODE=102;
Output:
(b) To display details of all products in the stock table in descending order of Stock date.
Sol:
mysql> SELECT * FROM STOCK ORDER BY STOCKDATE DESC;
Output:
(c) To display maximum unit price of products for each dealer individually as
per dcodefrom the table Stock.
Sol:
(d) To display the Pname and Dname from table stock and dealers.
Sol:
mysql> SELECT PNAME,DNAME FROM STOCK S,DEALERS D
WHERE S.DCODE=D.DCODE;
Output:
Program 13
Objective: Program to connect with database and store record of employee and
display records.
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :101
Enter Name :RAMESH
Enter Department :IT
Enter Salary :34000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :2
EMPNO NAME DEPARTMENT SALARY
101 RAMESH IT 34000
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice : 0
Program 14
Objective: 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
########################################
import mysql.connector as ms
db=ms.connect(host="localhost",
user="root",
passwd="DPS@123",
database="class_xii")
cn=db.cursor()
def insert_rec():
try:
while True:
rn=int(input("Enter roll number:"))
sname=input("Enter name:")
marks=float(input("Enter marks:"))
gr=input("Enter grade:")
cn.execute("insert into student values({},'{}',{},'{}')".format(rn,sname,marks,gr))
db.commit()
ch=input("Want more records? Press (N/n) to stop entry:")
if ch in 'Nn':
print("Record Inserted ")
break
except Exception as e:
print("Error", e)
def update_rec():
try:
rn=int(input("Enter rollno to update:"))
marks=float(input("Enter new marks:"))
gr=input("Enter Grade:")
cn.execute("update student set marks={},gr='{}' where rn={}".format(marks,gr,rn))
db.commit()
print("Record Updated .... ")
except Exception as e:
print("Error",e)
def delete_rec():
try:
rn=int(input("Enter rollno to delete:"))
cn.execute("delete from student where rn={}".format(rn))
db.commit()
print("Record Deleted ")
except Exception as e:
print("Error",e)
def view_rec():
try:
cn.execute("select * from student")
records = cn.fetchall()
for record in records:
print(record)
#db.commit()
#print("Record...")
except Exception as e:
print("Error",e)
db = ms.connect( host="localhost",
user="root",
passwd="root",
database="class_xii")
cn = db.cursor()
while True:
print("MENU\n1. Insert Record\n2. Update Record \n3. Delete Record\n4. Display Record \n5.Exit")
ch=int(input("Enter your choice<1-4>="))
if ch==1:
insert_rec()
elif ch==2:
update_rec()
elif ch==3:
delete_rec()
elif ch==4:
view_rec()
elif ch==5:
break
else:
print("Wrong option selected")
OUTPUT:
MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=1
Enter roll number:101
Enter name:Ramesh
Enter marks:85
Enter grade:A
Want more records? Press (N/n) to stop entry:n
Record Inserted
MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=4
(101, 'Ramesh', 85.0, 'A')
MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=2
Enter rollno to update:101
Enter new marks:58
Enter Grade:B
Record Updated....
MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=4
(101, 'Ramesh', 58.0, 'B')
MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=5