Practical 2024 25
Practical 2024 25
Ex No: 1 List
Date:
1. Write a python program to pass list to a function and double the odd
values and half even values of a list and display list element after
changing.
AIM: To write a program to pass list to a function and double the odd values
and half even values of a list and display list element after changing .
PROGRAM CODE:
def fun(lst):
list2=[ ]
for i in range(0, len(lst)):
if(lst[i]%2==0):
eve =lst[i]/2
list2.append(eve)
else:
eve=lst[i]*2
list2.append(eve)
print(list2)
OUTPUT:
RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------
Ex No: 2 Tuple
Date:
PROGRAM CODE:
def fun(lst):
eve=0
odd=0
for i in range(0, len(lst)):
if lst[i]%2 == 0:
eve+=1
else:
odd+=1
print("Number of even numbers :", eve, "Number of odd numbers :", odd)
1 | MVM
Class: 12 CS PRACTICALS: 2024-25
fun(x)
OUTPUT
Enter a tuple :(1,2,3,4,5,6,7)
Number of even numbers : 3 Number of odd numbers : 4
RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------
Ex No: 3 Dictionary
Date:
3. Write a Python program to function with key and value, and update
value at that key in dictionary entered by user.
AIM:To write a program to function with key and value, and update value at
that key in dictionary entered by user.
PROGRAM CODE:
def fun(d,k):
value2=eval (input("Enter the value :"))
d[k]=value2
print ("Updated dictionary :", d)
x=int (input ("Number of pairs in dictionary :"))
dic={ }
for i in range(x):
key = eval (input ("Enter the key :"))
value = eval(input ("Enter the value :"))
dic[key]=value
print ("Original dictionary :", dic)
a= eval(input("Enter the key whose value you want to change :"))
fun (dic, a)
OUTPUT
RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------
2 | MVM
Class: 12 CS PRACTICALS: 2024-25
AIM:To write a program to pass a string to a function and count how many
vowels present in the string.
PROGRAM CODE :
def fun(lst):
count = 0
for i in range (0, len(lst)):
if lst[i]=="a" or lst[i]=="A":
count+=1
elif lst[i]=="e" or lst[i]=="E":
count+=1
elif lst[i]=="i" or lst[i]=="I":
count+=1
elif lst[i]=="o" or lst[i]=="O":
count+=1
elif lst[i]=="u" or lst[i]=="U":
count+=1
print("Number of vowels :", count)
a=input("Enter a String :")
fun(a)
OUTPUT
INPUT
def fun():
import random
r=random.randint(1,6)
print("Random numbers generated between 1 to 6 :", r)
fun()
OUTOUT
Random numbers generated between 1 to 6 : 5
RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------
3 | MVM
Class: 12 CS PRACTICALS: 2024-25
Date:
PROGRAM CODE:
c=str(input(" Enter sentence: "))
a=input("Enter the spacing :")
print("The string entered is a word : ", c.isalpha())
print("The string entered is lower case : ", c.lower())
print("The string entered is in lower case : ", c.islower())
print("The string entered is upper case : ", c.upper())
print("The string entered is in upper case : ", c.isupper())
print("The string entered after removing the space from left side : ", c.lstrip())
print("The string entered after removing the space from right side : ", c.rstrip())
print("The string entered contains whitespace :", c.isspace())
print("The string entered is titlecased :", c.istitle())
print("The string entered after joining with ", a, ":", a.join(c))
print("The string entered after swaping case : ", c.swapcase())
OUTPUT
RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------
7. Write a python program to read and display file content line by line with
each word separated by #.
AIM : To write a program to read and display file content line by line with each
word separated by #.
PROGRAM CODE:
a= open(r"f:\result.txt", "r")
lines=a.readlines()
4 | MVM
Class: 12 CS PRACTICALS: 2024-25
for le in lines:
x=le.split()
for y in x:
print(y+ "#", end=" ")
print(" ")
OUTPUT
RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------
8. Write a python program to remove all the lines that contain the character ‘a’
in a file and write it to another file.
AIM:To write a program to remove all the lines that contain the
character ‘a’ in a file and write it to another file.
PROGRAM CODE:
file=open(r"f:\result.txt", "r")
lines=file.readlines()
file.close()
file=open(r"f:\result.txt", "w")
file1=open(r"f:\result1.txt", "w")
for li in lines:
if 'a' in li:
file1.write(li)
else:
file.write(li)
print("lines that contain 'a' character are removed from result")
print ("Lines that contain 'a' character are added in result1 ")
file.close()
file1.close()
OUTPUT
RESULT:
5 | MVM
Class: 12 CS PRACTICALS: 2024-25
9. Write a python program to read characters from keyboard one by one, all
lower case letters gets stored inside a file “LOWER”, all uppercase letters gets
stored inside a file “UPPER”, and all other characters get stored inside
“OTHERS” 3
AIM: To write a program to read characters from keyboard one by one, all lower
case letters gets stored inside a file “LOWER”, all uppercase letters gets stored
inside a file “UPPER”, and all other characters get stored inside “OTHERS”
PROGRAM CODE:
f1=open(r"f:\lower.txt",'w')
f2=open(r"f:\upper.txt",'w')
f3=open(r"f:\others.txt",'w')
print('Input "`" to stop execution. ')
while True:
c=input("Enter a single character :")
if c=="~":
break
elif c.islower():
f1.write(c)
elif c.isupper():
f2.write(c)
else:
f3.write(c)
f1.close()
f2.close()
f3.close()
OUTPUT
Input "`" to stop execution.
Enter a single character :a
Enter a single character :b
Enter a single character :c
Enter a single character :d
Enter a single character :e
Enter a single character :f
Enter a single character :g
Enter a single character :h
Enter a single character :i
Enter a single character :j
Enter a single character :k
Enter a single character :l
Enter a single character :M
Enter a single character :N
Enter a single character :O
Enter a single character :P
Enter a single character :Q
Enter a single character :R
Enter a single character :S
Enter a single character :T
Enter a single character :U
Enter a single character :V
Enter a single character :W
Enter a single character :X
6 | MVM
Class: 12 CS PRACTICALS: 2024-25
RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------
10. Write a python program to create a binary file with name and roll number.
Search for a given roll number and display name, if not found display
appropriate message.
AIM: To write a program to create a binary file with name and roll number,
search for a given roll number and display name, if not found display
appropriate.
PROGRAM CODE:
import pickle
sdata={ }
slist=[]
total=int(input("Enter number of students : "))
for i in range(total):
sdata["Roll no:"]=int(input("Enter Roll no : "))
sdata["Name :"]=input("Enter Name :")
slist.append(sdata)
sdata={ }
a=open(r"f:\text.dat", "wb")
pickle.dump(slist, a)
a.close()
x=open(r"f:text.dat", "rb")
slist=pickle.load(x)
b=int(input("Enter the roll number of student to be searched :"))
7 | MVM
Class: 12 CS PRACTICALS: 2024-25
y=False
for text in slist:
if(text["Roll no:"]==b):
y=True
print(text["Name :"], "Found in file")
if(y==False):
print("Data of student not found :")
OUTPUT 1:
Enter number of students : 3
Enter Roll no : 1
Enter Name :hema
Enter Roll no : 2
Enter Name :arun
Enter Roll no : 3
Enter Name :archana
Enter the roll number of student to be searched :5
Data of student not found :
OUTPUT 2:
Enter number of students : 3
Enter Roll no : 1
Enter Name :hema
Enter Roll no : 2
Enter Name :arun
Enter Roll no : 3
Enter Name :anu
Enter the roll number of student to be searched :3
anu Found in file
RESULT:
The above program has been executed successfully.
----------------------------------------------------------------------------------------------
Ex No: 11 File Handling - Create Binary file for students details and
update the details
Date:
11. Write a python program to create a binary file with roll number, name and
marks, input a roll number and update the marks.
AIM:To write a program to create a binary file with roll number, name and
marks, input a roll number and update the marks.
PROGRAM CODE:
import pickle
sdata={ }
total=int(input("Enter number of students :"))
a=open(r"f:\bin.dat", "wb")
for i in range(total):
sdata["Roll no"]=int (input("Enter roll no :"))
sdata["Name"]=input("Enter Name :")
sdata ["Marks"]=float(input("Enter marks :"))
pickle.dump(sdata,a)
sdata={ }
a.close()
#updating marks
8 | MVM
Class: 12 CS PRACTICALS: 2024-25
found=False
rollno=int(input("Enter roll number :"))
a=open(r"f:\bin.dat", "rb+")
try:
while True:
pos=a.tell()
sdata=pickle.load(a)
if (sdata["Roll no"]==rollno):
sdata["Marks"]=float(input("Enter new marks :"))
a.seek(pos)
pickle.dump(sdata, a)
found=True
except EOFError:
if found==False:
print("Roll number not found ")
else:
print("Students marks updated successfully")
a.close()
OUTPUT
RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------
Date:
12. Write a program to store customer data into a binary file cust.dat using a
dictionary and print them on screen after reading them. The customer data
contains ID as key, and name, city as values.
AIM: To Write a program to store customer data into a binary file cust.dat
using a dictionary and print them on screen after reading them. The customer
data contains ID as key, and name, city as values.
PROGRAM CODE:
import pickle
def bin2dict():
f = open("cust.dat","wb")
d = {'C0001':['Subham','Ahmedabad'],
'C0002':['Bhavin','Anand'],
'C0003':['Chintu','Baroda']}
pickle.dump(d,f)
f.close()
9 | MVM
Class: 12 CS PRACTICALS: 2024-25
f = open("cust.dat","rb")
d = pickle.load(f)
print(d)
f.close()
bin2dict()
OUTPUT:
{'C0001': ['Subham', 'Ahmedabad'], 'C0002': ['Bhavin', 'Anand'], 'C0003':
['Chintu', 'Baroda']}
RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------
Date:
13. Write a function to count records from the binary file marks.dat.
AIM:To Write a function to count records from the binary file marks.dat.
PROGRAM CODE:
import pickle
def count_records():
f = open("cust.dat","rb")
cnt=0
try:
while True:
data = pickle.load(f)
for s in data:
cnt+=1
except Exception:
f.close()
print("The file has ", cnt, " records.")
count_records()
OUTPUT:
The file has 3 records.
RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------
Date:
14. Write a python program to create a CSV file with empid, name and mobile
no. and search empid, update the record and display the records.
AIM: To write a program to create a CSV file with empid, name and mobile no.
and search empid, update the record and display the records.
10 | MVM
Class: 12 CS PRACTICALS: 2024-25
PROGRAM CODE:
import csv
with open('employee.csv', 'a') as csvfile:
mywriter=csv.writer(csvfile, delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee ID :"))
name=input("Enter Employee Name :")
mobno=int(input("Enter Employee Mobile No :"))
mywriter.writerow([eno, name, mobno])
ans=input("Do you want to Enter more data? (y/n):")
ans='y'
OUTPUT
Enter Employee ID :1
Enter Employee Name :aswath
Enter Employee Mobile No :9365550777
RESULT:
The above program has been executed successfully.
---------------------------------------------------------------------------------------
11 | MVM
Class: 12 CS PRACTICALS: 2024-25
PROGRAM CODE:
stack =[]
def view():
for x in range (len(stack)):
print(stack[x])
def push():
item=int(input("Enter integer value"))
stack.append(item)
def pop():
if(stack==[]):
print("Stack is empty")
else:
item=stack.pop(-1)
print("Deleted elements:", item)
def peek():
item=stack[-1]
print("Peeked element:", item)
print("Stack operation")
print("****************")
print("1. Push")
print("2. View ")
print("3. Pop ")
print("4. Peek ")
while True:
choice=int(input("Enter your choice : "))
if choice==1:
push()
elif choice==2:
view()
elif choice==3:
pop()
elif choice==4:
peek()
else:
print("Wrong choice")
OUTPUT:
Stack operation
****************
1. View
2. Push
3. Pop
4. Peek
Enter your choice : 1
Enter integer value11
12 | MVM
Class: 12 CS PRACTICALS: 2024-25
Create two tables for stationary and consumer and execute the given
commands using SQL.
Table: Stationary
S_ID StationaryName Company Price
DP01 Dot Pen ABC 10
PL02 Pencil XYZ 6
ER05 Eraser XYZ 7
PL01 Pencil CAM 5
GP02 Gel Pen ABC 15
Table: Consumer
C_ID ConsumerName Address S_ID
01 Good Learner Delhi PL01
06 Write Well Mumbai GP02
12 Topper Delhi DP01
15 Write & Draw Delhi PL02
16 Motivation Bangalore PL01
AIM: To create two tables for stationary and consumer and execute the
given commands using SQL.
i) To display the details of those Consumers whose Address is Delhi.
ii) To display the details of Stationary whose Price is in the range of 8 to
15 (Both values included).
13 | MVM
Class: 12 CS PRACTICALS: 2024-25
PROGRAM CODE:
Create table stationary(S_ID char(5) not null primary key, stationaryname
char(25), company char(5), price int);
insert into stationary values("DP01","Dot pen","ABC",10);
insert into stationary values("PL02","Pencil","XYZ",6);
insert into stationary values("ER05","Eraser","XYZ",7);
insert into stationary values("PL01","Pencil","CAM",5);
insert into stationary values("GP02","Gel pen","ABC",15);
14 | MVM
Class: 12 CS PRACTICALS: 2024-25
RESULT:
The above program has been executed successfully.
---------------------------------------------------------------------------------------
Date:
1) Create two tables for item and traders and execute the given commands
using SQL.
Table: Item
Code IName Qty Price Company TCode
1001 Digital Pad 121 120 11000 XENTIA T01
1006 LED Screen 40 70 38000 SANTORA T02
1004 Car Gps System 50 2150 GEOKNOW T01
1003 Digital Camera 12X 160 8000 DIGICLICK T02
1005 Pen Drive 32GB 600 1200 STOREHOME T03
Table: Traders
TCode TName City
T01 Electronics Sales Mumbai
T03 Busy Store Corp Delhi
T02 Disp House Inc Chennai
AIM: To Create two tables for item and traders and execute the given
commands using SQL.
i) To display the details of all the items in ascending order of item
names (i.e. IName).
ii) To display item name and price of all those items, whose price is in
the range of 10000 and 22000 (both values inclusive).
iii) To display the number of items, which are traded by each trader. The
expected output of this query should be
T01 2
T02 2
T03 1
15 | MVM
Class: 12 CS PRACTICALS: 2024-25
iv) To display the price, item name (i.e. IName) and quantity (i.e. Qty) of
those items which have quantity more than 150.
v) To display the name of those traders, who are either from Delhi or
from Mumbai.
PROGRAM CODE:
Create table ITEM (Code int, IName char(25), Qty int, Price int, Company
char(25), Tcode char(5));
Insert into Item values(1001, “DIGITAL PAD 121”, 120, 11000,
“XENTIA”,”T01”);
Insert into Item values(1006, “LED SCREEN 40”, 70, 38000,
“SANTORA”,”T02”);
Insert into Item values(1004, “CAR GPS SYSTEM”, 50, 2150,
“GEOKNOW”,”T01”);
Insert into Item values(1003, “DIGITAL CAMERA 12X”, 160, 8000,
“DIGICLICK”,”T02”);
Insert into Item values(1005, “PEN DRIVE 32GB”, 600, 12000,
“STOREHOME”,”T03”);
ii) Select IName, Price from ITEM where Price between 10000 and 22000;
RESULT:
The above program has been executed successfully.
---------------------------------------------------------------------------------------
16 | MVM
Class: 12 CS PRACTICALS: 2024-25
Create two tables for Doctor and Salary and execute the given commands using
SQL.
Table: Doctor
ID Name Dept Sex Experience
101 John ENT M 12
104 Smith ORTHOPEDIC M 5
107 George CARDIOLOGY M 10
114 Lara SKIN F 3
109 K George MEDICINE F 9
105 Johnson ORTHOPEDIC M 10
117 Lucy ENT F 3
111 Bill MEDICINE F 12
130 Morphy ORTHOPEDIC M 15
Table: Salary
ID Basic Allowance Consultation
101 12000 1000 300
104 23000 2300 500
107 32000 4000 500
114 12000 5200 100
109 42000 1700 200
105 18900 1690 300
130 21700 2600 300
AIM: To Create two tables for Doctor and Salary and execute the given
commands using SQL.
i) To display Name of all doctors who are in “Medicine” having more
than 10 years experience from table Doctor.
ii) To display the average salary of all Doctors working in “ENT”
department using the tables Doctor and Salary (Salary = Basic +
Allowance).
iii) To display minimum Allowance of female doctors.
iv) To display Doctor.Id. Name from the table Doctor and Basic,
Allowances from the table Salary with their corresponding matching
ID.
v) To display distinct department from the table Doctor.
PROGRAM CODE:
Create Table DOCTOR(ID int not null primary key, Name char(25), Dept
char(25), sex char, Experience int);
Insert into DOCTOR VALUES(101, “John”, “ENT”, “M”, 12);
Insert into DOCTOR VALUES(104, “Smith”, “ORTHOPEDIC”, “M”, 5);
Insert into DOCTOR VALUES(107, “George”, “CARDIOLOGY”, “M”, 10);
Insert into DOCTOR VALUES(114, “Lara”, “SKIN”, “F”, 3);
17 | MVM
Class: 12 CS PRACTICALS: 2024-25
Create Table SALARY (ID int, BASIC int, ALLOWANCE int, CONSULTATION
int);
Insert into SALARY VALUES(101,12000,1000,300);
Insert into SALARY VALUES(104,23000,2300,500);
Insert into SALARY VALUES(107,32000,4000,500);
Insert into SALARY VALUES(114,12000,5200,100);
Insert into SALARY VALUES(109,42000,1700,200);
Insert into SALARY VALUES(105,18900,1690,300);
Insert into SALARY VALUES(130,21700,2600,300);
OUTPUT:
i) Select Name from DOCTOR where Dept=”Medicine”and Experience >
10;
ii) Select avg(basic + allowance) “avg salary” from DOCTOR, Salary where
DOCTOR.ID and DEPT=”ENT”;
RESULT:
The above program has been executed successfully.
---------------------------------------------------------------------------------------
18 | MVM
Class: 12 CS PRACTICALS: 2024-25
19. Write a python program (integrate python with SQL) to fetch the records
from table.
AIM: To write a python program (integrate python with SQL) to fetch the
records from table.
PROGRAM CODE:
import mysql.connector as sqltor
mycon=sqltor.connect(host="localhost",
user="root",password="1234",database="trinity")
if mycon.is_connected()==False:
print("Error connecting to Mysql database")
cursor=mycon.cursor()
cursor.execute("select * from student")
data=cursor.fetchall()
count=cursor.rowcount
for row in data:
print(row)
mycon.close()
OUTPUT:
(1001, 'Arun', 23, 34, 45, 50, 44, 'Coimbatore')
(1002, 'Abhishek', 44, 50, 45, 35, 50, 'Coimbatore')
(1002, 'Swarna', 47, 50, 35, 39, 50, 'Coimbatore')
RESULT:
The above program has been executed successfully.
---------------------------------------------------------------------------------------
20. Write a python program (integrate python with SQL) to count records from
table.
AIM: To write a python program (integrate python with SQL) to count records
from table.
Program code:
import mysql.connector as sqltor
mycon=sqltor.connect(host="localhost",
user="root",password="1234",database="trinity")
if mycon.is_connected()==False:
print("Error connecting to Mysql database")
cursor=mycon.cursor()
cursor.execute("select * from student")
data=cursor.fetchone()
count=cursor.rowcount
print("Total number of rows retrieved from resultset : ", count)
data=cursor.fetchone()
19 | MVM
Class: 12 CS PRACTICALS: 2024-25
count=cursor.rowcount
print("Total number of rows retrieved from resultset : ", count)
data=cursor.fetchmany(3)
count=cursor.rowcount
print("Total number of rows retrieved from resultset : ", count)
mycon.close()
OUTPUT:
Total number of rows retrieved from resultset : 1
Total number of rows retrieved from resultset : 2
Total number of rows retrieved from resultset : 3
RESULT:
The above program has been executed successfully.
---------------------------------------------------------------------------------------
21. Write a python program (integrate python with SQL) to search the records
from table.
AIM: To write a python program (integrate python with SQL) to search the
records from table.
PROGRAM CODE:
import mysql.connector as mc
mycon=mc.connect(host="localhost",user="root",password="1234",database="d
b12")
if mycon.is_connected():
print("py->sql connected")
eno=int(input("Enter num: "))
mcursor=mycon.cursor()
mcursor.execute("select * from emp")
allrow=mcursor.fetchall()
for row in allrow:
if row[0]==eno:
print(row)
mycon.commit()
mycon.close()
OUTPUT:
py->sql connected
Enter num: 102
(102, 'abhishek', 35, 'coimbatore')
RESULT:
The above program has been executed successfully.
---------------------------------------------------------------------------------------
20 | MVM
Class: 12 CS PRACTICALS: 2024-25
22. Write a python program (integrate python with SQL) to delete the records
from table.
AIM : To write a python program (integrate python with SQL) to delete the
records from table.
PROGRAM CODE:
import mysql.connector as mc
mycon=mc.connect(host="localhost",user="root",password="1234",database="d
b12")
if mycon.is_connected():
print("py->sql connected")
eno=int(input("Enter num: "))
mcursor=mycon.cursor()
mcursor.execute("select * from emp")
allrow=mcursor.fetchall()
for row in allrow:
if row[0]==eno:
mcursor.execute("delete from emp where eno={}".format(eno))
mcursor.execute("select * from emp")
print(mcursor.fetchall())
mycon.commit()
mycon.close()
OUTPUT:
py->sql connected
Enter num: 101
[(102, 'abhishek', 35, 'coimbatore'), (103, 'aashikk', 38, 'coimbatore')]
21 | MVM