Practical File Class 12
Practical File Class 12
RANIPUR, HARIDWAR
PRACTICAL FILE
COMPUTER SCIENCE
SESSION: 2024-25
INDEX
1 Write a program using user defined function FIND_LEN(str) that reads a string/line and print
each individual word of the line along with the length of the word.
2 Write a program using user defined function SQUARE_LIST(L), where L is the list of elements
passed as argument to the function. The function returns another list named ‘SList’ that stores the
Squares of all Non-Zero Elements of L.
For example: If L contains [9,4,0,11,0,6,0]
4 Write a program that allow the user to enter the eid, ename, age, dept of n employees and write the
detail of these employees in the text file “emp.text”.
5 Write a program to add two more records i.e. detail of two more employees in the file “emp.text”
created in the program no. 3 and then display the contents of the file.
6 Write a program using user defined function count_line() that count the number of lines starting with letter ‘A’ o
‘T’ from the file “data.text” and display it on the screen.
7 Write a program using user defined function count_word() to count the words "are" and "the" in the file
“stud.text”.
8 Write a program using user defined function count_vowel() to count the number of vowels in the
file “data.txt” .
9 Write a program to write multiple records of students(rno, name, subject, marks) in form of lists in
a file "dps.dat" and then display all data on the screen.
10 Write a program using user defined function CopyBinary() that will copy the data from the binary
file "source.dat" to "target.dat" .
11 Write a program to display the detail of the employee from the file "emp.dat" as per the eid
entered by the user. Consider the binary file “emp.dat” that contains the information of employees
like (eid, ename, salary) in form of list.
12 Consider a binary file ”flight.dat” that store the information of flights like (fno, source,
destination) in form of list . WAP to display information of those flights whose starting point is
Delhi from the binary file "flight.dat".
13 Write a program using user defined function in Python WordCount() to read a text file “Mydiary.txt”
and display the number of words present in each line.
Example:
If the file content is as follows:
Updated information
As simplified by official websites.
14 Write a program using user defined function INDEX_LIST(L), where L is the list of elements
passed as argument to the function. The function returns another list named ‘IndList’ that stores
the indices of all Non-Zero Elements of L.
For example:
If L contains [12,4,0,11,0,35]
20 Write the SQL commands for the question from (i) to (x) on the basis of table TEACHER given
below:
TEACHER
TNo Tname Gender Age Department Salary DOB
101 Ashok Kumar M 28 English 15000 2010-10-13
102 Rakesh Sharma M 32 Mathematics 25000 2008-08-23
103 Richa Saini F 27 Computer 22000 2014-07-15
104 Amit Gupta M 35 Science 17000 NULL
105 Sandeep Goyal M 42 Computer 19000 2005-12-27
106 Sangeeta F 33 English 14000 2008-11-17
107 Jyoti Sharma F 29 Hindi 12000 2012-05-13
108 Manoj Kumar M 40 Science 21000 NULL
109 Rajendra Kapoor M 36 Art 16000 2004-04-25
110 Vinay Kumar M 32 English 18000 2011-03-10
Table : COACHES
SportsPerson Gender CoachID
AJAY M 101
SEEMA F 102
VINOD M 104
TANEJA F 103
For Example:
If the sample Content of the list is as follows:
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
Sample Output of the code should be:
38 22 98 56 34 12
29 Ankur has a list containing 10 integers. You need to help him create a program with separate user
defined functions to perform the following operations based on this list.
● Traverse the content of the list in reverse order i.e. read the content of list from the last(end)
and push the numbers into a stack.
● Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows:
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
Sample Output of the code should be:
12 13 34 56 21 79 98 22 35 38
DATABASE CONNECTIVITY
Consider the table “student” in database “test”
30 WAP to display the detail of all students from the table “student” of database “dps”.
31 WAP to display the detail of student whose rollno is entered by the user from the table “student”
of database “dps”.
32 WAP to display the detail of all students who have submitted the project from the table “student”
of database “dps”.
33 WAP to insert a new record in the table “student” of database “dps”.
34 WAP to display to increase the marks by 5 of all the students of section ‘A’ from the table
“student” of database “dps”.
35 WAP to display to remove the record of the students whose rollno is entered by the user from the
table “student” of database “dps”.
PROGRAM 1: Write a program using user defined function FIND_LEN(str) that reads a
string/line and print each individual word of the line along with the length of the word.
def FIND_LEN(str):
str=input('enter a line:')
a=str.split(' ')
for i in a:
print(i ,':', len(i))
FIND_LEN(str)
OUTPUT:
PROGRAM 2: Write a program using user defined function SQUARE_LIST(L), where L is
the list of elements passed as argument to the function. The function returns another list named
‘SList’ that stores the Squares of all Non-Zero Elements of L.
def SQUARE_LIST():
L=eval(input("enter a list of integers: "))
SList=[]
for i in L:
if i != 0:
SList.append(i*i)
print('The list enteredby you is :', L)
print('The list of square of non zero elements is :', SList)
SQUARE_LIST()
OUTPUT:
PROGRAM 3: Write a function program using user defined function REVERSE_DATA(str) that
reads a string/sentence and create a new sentence/ string storing each of the word in its reverse form.
For example:
If input sentence/string : Board exams are coming
print("Input string:",user)
print("Output string:",result)
OUTPUT:
PROGRAM 4: Write a program that allow the user to enter the eid, ename, age, dept of n
employees and write the detail of these employees in the text file “emp.text”.
f=open('D:/emp.txt','w')
n=int(input('how many records do you wish to enter: '))
for i in range (0,n):
eid=input(' enter the employee id:')
ename=input(' enter the name of the employee:')
age=input(' enter the age of the employee:')
dept=input(' enter the department of the employee:')
a= eid + ename + age + dept
f.write(a)
f.close()
OUTPUT:
PROGRAM 5: Write a program to add two more records i.e. detail of two more employees in the
file “emp.text” created in the program no. 4 and then display the contents of the file.
f=open('D:/emp.txt','a')
for i in range (0,2):
eid=input(' enter the employee id:')
ename=input(' enter the name of the employee:')
age=input(' enter the age of the employee:')
dept=input(' enter the department of the employee:')
a= eid + ename + age + dept
f.write(a)
f.close()
OUTPUT:
PROGRAM 6: Write a program using user defined function count_line() that count the number of
lines starting with letter ‘A’ or ‘T’ from the file “data.text” and display it on the screen.
def count_line():
count=0
data=fp.readlines()
for i in data:
if i[0].lower()=="t" or i[0].lower()=="a" :
count+=1
return count
fp=open("D:/data.txt","r")
c=count_line()
print("Number of lines starting with 'T' or 'A':",c)
OUTPUT:
PROGRAM 7: Write a program using user defined function count_word() to count the words
"are" and "the" in the file “stud.text”.
def count_word():
c1,c2=0,0
data=fp.readlines()
for i in data:
for j in i.split():
if j.lower()=="are":
c1+=1
elif j.lower()=="the":
c2+=1
return c1,c2
OUTPUT:
PROGRAM 8: Write a program using user defined function count_vowel() to count the number of vowels
in the file “data.txt”.
def count_vowel():
c=0
vowels="aeiou"
for line in fp.readlines():
for vowel in vowels:
c+=(line.lower()).count(vowel)
return c
fp=open("D:/data.txt","r")
count=count_vowel()
print("Number of vowels:",count)
OUTPUT:
PROGRAM 9: Write a program to write multiple records of students(rno, name, subject,
marks) in form of lists in a file "dps.dat" and then display all data on the screen.
import pickle
fp=open("dpt.dat","ab+")
while True:
rno=int(input("Enter the rno: "))
name=input("Enter the name: ")
subject=input("Enter the subject: ")
marks=int(input("Enter the marks: "))
record=[rno,name,subject,marks]
pickle.dump(record,fp)
ch=input("Do you want to enter more records (Y/N): ")
if ch.lower()=="n":
break
fp.seek(0,0)
while True:
try:
data=pickle.load(fp)
print(data)
except EOFError:
break
fp.close()
OUTPUT:
PROGRAM 10: Write a program using user defined function CopyBinary() that will copy
the data from the binary file "source.dat" to "target.dat".
import pickle
def CopyBinary(f1,f2):
while True:
try:
data=pickle.load(f1)
pickle.dump(data,f2)
except EOFError:
break
f1=open("D:/source.dat","rb")
f2=open("target.dat","wb")
CopyBinary(f1,f2)
f1.close()
f2.close()
PROGRAM 11: Write a program to display the detail of the employee from the file
"emp.dat" as per the eid entered by the user. Consider the binary file “emp.dat” that
contains the information of employees like (eid, ename, salary) in form of list.
import pickle
OUTPUT:
PROGRAM 12: Consider a binary file ”flight.dat” that store the information of flights like
(fno, source, destination) in form of list . WAP to display information of those flights whose
starting point is Delhi from the binary file "flight.dat".
import pickle
read=0
fp=open("D:/flight.dat","rb")
while True:
try:
data=pickle.load(fp)
if data[1].lower()=="delhi":
print("fno:",data[0])
print("source:",data[1])
print("destination:",data[2])
read+=1
except EOFError:
break
fp.close()
if read==0:
print("No record found!!")
OUTPUT:
PROGRAM 13: Write a program using user defined function in Python WordCount() to
read a text file “Mydiary.txt” and display the number of words present in each line.
def WordCount(lines):
count=[]
for line in lines:
count.append(len(line.split()))
return count
fp=open("D:/Mydiary.txt")
lines=fp.readlines()
count=WordCount(lines)
for i in range(1,len(lines)+1):
print(f"Line No {i}: Words={count[i-1]}")
fp.close()
OUTPUT
PROGRAM 14: Write a program using user defined function INDEX_LIST(L), where L is
the list of elements passed as argument to the function. The function returns another list
named ‘IndList’ that stores the indices of all Non-Zero Elements of L.
def INDEX_LIST(L):
IndList=list()
for i in range(len(L)):
if L[i]!=0:
IndList.append(i)
return IndList
l=INDEX_LIST([12,4,0,11,0,35])
print(l)
OUTPUT
PROGRAM 15: Consider the binary file “emp.dat” that contains the information of
employees like (eid, ename, salary) in form of list. Write a program to increase the salary of
those employees by 2000 whose salary is less than 25000 from the binary file “emp.dat”.
import pickle as pc
f=open("emp.dat","rb+")
flag=0
try:
while True:
flag=f.tell()
record=pc.load(f)
if record[2]<25000:
record[2]+=2000
f.seek(flag)
pc.dump(record,f)
except EOFError:
print(".")
finally:
f.close()
OUTPUT
PROGRAM 16: WAP to create a csv file “student.csv” to store data (rollno, name, marks).
Obtain the detail of five students from the user and write it in the file “student.csv”
import csv
fp=open("student.csv","w",newline="")
writer=csv.writer(fp)
writer.writerow(["Roll No","Name","Marks"])
for i in range(5):
rollno=int(input("\nEnter the roll no: "))
name=input("Enter the name: ")
marks=int(input("Enter the marks: "))
record=[rollno,name,marks]
writer.writerow(record)
fp.close()
OUTPUT
PROGRAM 17: Sameer is a Python programmer. He has created a csv file named “furniture.csv”
to store the details of the different furnitures in form a list [Fid, Fname, Fprice] ...
import csv
def addDetail():
fp=open("furniture.csv","w",newline="")
writer=csv.writer(fp)
writer.writerow(["Fid","Fname","Fprice"])
while True:
fid=int(input("Enter the Fid: "))
fname=input("Enter the Fname: ")
fprice=int(input("Enter the Fprice: "))
record=[fid,fname,fprice]
writer.writerow(record)
def search():
fp=open("furniture.csv","r")
reader=csv.reader(fp)
i=0
for record in reader:
if i!=0:
if int(record[2])>10000:
print(record)
i+=1
fp.close()
addDetail()
search()
OUTPUT
PROGRAM 18: Tushar is a Python programmer working in a school. For the Annual
Examination , he has created a csv file named dps.csv to store the result of the students in
different subjects in form a list …
import csv
def addStudent():
fp=open("dps.csv","w",newline="")
writer=csv.writer(fp)
writer.writerow(["Rollno","Name","Subject","Marks"])
for i in range(5):
rollno=int(input("Enter the rollno: "))
name=input("Enter the name: ")
subject=input("Enter the subject: ")
marks=int(input("Enter the marks: "))
record=[rollno,name,subject,marks]
writer.writerow(record)
fp.close()
def search():
fp=open("dps.csv","r")
reader=csv.reader(fp)
i=0
for record in reader:
if i!=0:
if int(record[3])>75:
print(record)
i+=1
fp.close()
addStudent()
search()
OUTPUT
PROGRAM 19: Write SQL query to create a table ‘Workshop’ with the following structure:
OUTPUT:
PROGRAM 20: Write the SQL commands for the question from (i) to (x) on the basis of table
TEACHER given below:
TEACHER
Depa
Roll Nam Gen rtme
no e Age der nt Fee
Anki Com
101 t 20 M puter 700
Hind
102 Payal 23 F i 400
Mohi Math
103 t 27 M s 900
Priya Com
104 nka 19 F puter 700
Anjal Engli
105 i 25 F sh 600
Sank Hind
106 et 29 M i 400
Rahu Com
107 l 31 M puter 700
Rash Math
108 mi 22 F s 900
Write SQL commands for the following statements :
(i) To display all the information about the students of Computer Department.
(ii) To display the name of male students only who are in Maths Department.
(iii) To increase the fee of all the students of computer department by 100
(iv) To display the average fee of student.
To delete the record of a student whose rollno is 107
PROGRAM 24:
Consider the table Student given in Q.No. 23 and give the output of the following SQL queries:
(i) select count(*) from student where age > 24 ;
(ii) select Max(fee) from student where gender = ‘M’ ;
(iii) select name , age , department from student where fee between 700 and 900 ;
select name , age , gender from student where department in(‘Computer’ , ‘Hindi’) ;
i)
|COUNT(*)|
|--------|
| 4 |
ii)
|MAX(FEE)|
|--------|
| 900 |
iii)
|NAME |AGE| DEPARTMENT|
|-------------------------|
|ANKIT |20 | COMPUTER |
|MOHIT |27 | MATHS |
|PRIYANKA |19 | COMPUTER |
|RAHUL |31 | COMPUTER |
|RASHMI |22 | MATHS |
iv)
| NAME |AGE|GENDER|
|--------------------|
|ANKIT |20 | M |
|PAYAL |23 | F |
|PRIYANKA |19 | F |
|SANKET |29 | M |
|RAHUL |31 | M |
PROGRAM 25:
Table : CLUB
CoachID CoachName Age Sports DateofApp Pay Gender
101 KUKREJA 35 KARATE 1996-03-27 1000 M
102 RAVINA 34 KARATE 1998-01-20 1200 F
103 KARAN 34 SQUASH 1998-02-19 2000 M
104 TARUN 33 BASKETBALL 1998-01-01 1500 M
105 AMIT 36 SWIMMING 1998-01-12 750 M
106 RAHUL 36 SWIMMING 1998-02-24 800 M
107 DEEPAK 39 SQUASH 1998-02-20 2200 M
108 MOHIT 39 KARATE 1998-02-22 1100 M
109 SHALINI 37 SWINMMING 1998-01-13 900 F
110 SEEMA 41 BASKETBALL 1998-02-19 1700 F
111 ABHISHEK 37 FOOTBALL 1996-02-15 1100 M
Table : COACHES
AJAY M 101
SEEMA F 102
VINOD M 104
TANEJA F 103
PROGRAM 26:
Consider the following tables CLUB and COACH given in Q.No.23. Give the output of the following
SQL queries..
1) SELECT COUNT(DISTINCT SPORTS) FROM CLUB;
2) SELECT MIN(AGE) FROM CLUB WHERE GENDER=’F’;
3) SELECT CoachID, CoachName FROM CLUB WHERE PAY BETWEEN 1000 AND 1500;
SELECT CoachName, Age, Sports, SportsPerson, Pay FROM CLUB, COACHES WHERE
CLUB.CoachID = COACHES.CoachID AND Pay>1000;
1.
|COUNT(SPORTS)|
|-------------|
| 5 |
2.
|MIN(AGE)|
|--------|
| 34 |
3.
|COACHID|COACHNAME|
|-----------------|
|101 | KUKREJA |
|102 | RAVINA |
|104 | TARUN |
|108 | MOHIT |
|111 | ABHISHEK |
4.
|COACHNAME|AGE|SPORTS |SPORTSPERSON|PAY |
|-------------------------------------------|
|RAVINA |34 |KARATE |SEEMA |1200|
|KARAN |34 |SQUASH |TANEJA |2000|
|TARUN |33 |BASKETBALL |VINOD |1500|
PROGRAM 27:
A list, NList contains following record as list elements: [RollNo, SName, marks] Each of these records
are nested together to form a nested list. Write the following user defined functions in Python to
perform the specified operations on the stack named travel.
(i) Push_Element(NList): It takes the nested list as an argument and pushes a list object containing
marks which are more than 90 into the stack.
(ii) Pop_Element(): It pops the objects from the stack and displays them. Also, the function should
display “Stack Empty” when there are no elements in the stack.
stack=[]
NList=[[11,"Sarthak",92], [12, "Hardik", 95], [13, "Ravi", 80], [14, "Tushar", 99], [15, "Sangeeta", 75]]
def Push_Element(NList):
for List in NList:
if List[2]>90:
stack.append(List)
def Pop_Element():
while len(stack):
print(stack.pop())
else:
print("Stack is empty.")
Push_Element(NList)
Pop_Element()
OUTPUT:
stack=[]
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
def Push_Element(N):
for i in N:
if i%2==0:
stack.append(i)
def Pop_Element():
while len(stack):
print(stack.pop(),end=" ")
Push_Element(N)
Pop_Element()
Output:
PROGRAM 29: Ankur has a list containing 10 integers. You need to help him create a
program with separate user defined functions to perform the following operations based on
this list.
(i) Traverse the content of the list in reverse order i.e. read the content of list from the
last(end) and push the numbers into a stack.
(ii) Pop and display the content of the stack.
stack=[]
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
def Push_Element(N):
for i in range(len(N)-1,-1,-1):
stack.append(N[i])
def Pop_Element():
while len(stack):
print(stack.pop(),end=' ')
Push_Element(N)
Pop_Element()
OUTPUT
PROGRAM 30: WAP to display the detail of all students from the table “student” of
database “dps”.
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root", database="dps")
if mydb.is_connected() == False:
print(“Error in connecting to MySQL database”)
mycursor=mydb.cursor()
mycursor.execute("select * from student")
for i in mycursor:
print(i)
mydb.close()
PROGRAM 31: WAP to display the detail of student whose rollno is entered by the user
from the table “student” of database “dps”.
import mysql.connector
n = int(input("Enter any roll number"))
mydb = mysql.connector.connect(host="localhost",user="root", database="dps")
if mydb.is_connected() == False:
print(“Error in connecting to MySQL database”)
mycursor=mydb.cursor()
mycursor.execute("select * from student where rollno=%s" % (n,))
for i in mycursor:
print(i)
mydb.close()
PROGRAM 32: WAP to display the detail of all students who have submitted the project
from the table “student” of database “dps”.
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root", database="dps")
if mydb.is_connected() == False:
print(“Error in connecting to MySQL database”)
mycursor=mydb.cursor()
mycursor.execute("select * from student where Project='submitted'")
for i in mycursor:
print(i)
mydb.close()
PROGRAM 33: WAP to insert a new record in the table “student” of database “dps”.
import mysql.connector
r = int(input("Enter rollno"))
n = input("Enter name")
m = float(input("Enter marks"))
g = input("Enter grade")
s = input("Enter section")
p = input("Enter project")
mydb = mysql.connector.connect(host="localhost",user="root", database="dps")
if mydb.is_connected() == False:
print(“Error in connecting to MySQL database”)
mycursor=mydb.cursor()
mycursor.execute("insert into student values({},'{}',{},'{}','{}','{}')".format(r,n,m,g,s,p))
mydb.commit()
mydb.close()
PROGRAM 34: WAP to display to increase the marks by 5 of all the students of section ‘A’
from the table “student” of database “dps”.
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root", database="test")
if mydb.is_connected() == False:
print(“Error in connecting to MySQL database”)
mycursor=mydb.cursor()
mycursor.execute("update student set marks = marks+5 where section = 'A’ ")
mydb.commit()
mydb.close()
PROGRAM 35: WAP to display to remove the record of the students whose rollno is entered
by the user from the table “student” of database “dps”.
import mysql.connector
n = int(input("Enter rollno"))
mydb = mysql.connector.connect(host="localhost",user="root", database="test")
if mydb.is_connected() == False:
print(“Error in connecting to MySQL database”)
mycursor=mydb.cursor()
mycursor.execute("delete from student where rollno={}".format(n))
mydb.commit()
mydb.close()