0% found this document useful (0 votes)
46 views21 pages

Practical 2024 25

Uploaded by

gamingpheonix752
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views21 pages

Practical 2024 25

Uploaded by

gamingpheonix752
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Class: 12 CS PRACTICALS: 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)

a=eval(input("Enter a list :"))


fun(a)

OUTPUT:

Enter a list :[1,2,3,4,5]


[2, 1.0, 6, 2.0, 10]

RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------

Ex No: 2 Tuple
Date:

2. Write a Python program input n numbers in tuple and pass it to


function to count how many even and odd numbers are entered.

AIM: To write a program to input n numbers in tuple and pass it to function to


count how many even and odd numbers are entered.

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)

x=eval(input("Enter a tuple :"))

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

Number of pairs in dictionary :3


Enter the key :"name"
Enter the value :"sanjay"
Enter the key :"age"
Enter the value :"15"
Enter the key :"class"
Enter the value :"10"
Original dictionary : {'name': 'sanjay', 'age': '15', 'class': '10'}
Enter the key whose value you want to change :"age"
Enter the value :16
Updated dictionary : {'name': 'sanjay', 'age': 16, 'class': '10'}

RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------

Ex No: 4 Count vowels in String


Date:

4. Write a Python program to pass a string to a function and count how


many vowels present in the string.

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

Enter a String :"computer Science"


Number of vowels : 6
RESULT:
The above program has been executed successfully.
----------------------------------------------------------------------------------------------

Ex No: 5 Generate Random Numbers


Date:

5. Write a Python program to generator (Random Number) that generates


random numbers between 1 and 6 (simulates a dice) using user defined
function.

AIM:To write a program to generator that generates random numbers between


1 and 6 using user defined function.

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.
-----------------------------------------------------------------------------------------------

Ex No: 6 String Functions

3 | MVM
Class: 12 CS PRACTICALS: 2024-25

Date:

6. Write a python program to implement python string functions.

AIM: To write a program to implement python string functions.

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

Enter sentence: "This is Computer Science period"


Enter the spacing :--
The string entered is a word : False
The string entered is lower case : "this is computer science period"
The string entered is in lower case : False
The string entered is upper case : "THIS IS COMPUTER SCIENCE PERIOD"
The string entered is in upper case : False
The string entered after removing the space from left side : "This is Computer
Science period"
The string entered after removing the space from right side : "This is Computer
Science period"
The string entered contains whitespace : False
The string entered is titlecased : False
The string entered after joining with -- : "--T--h--i--s-- --i--s-- --C--o--m--p--u--
t--e--r-- --S--c--i--e--n--c--e-- --p--e--r--i--o--d--"
The string entered after swapingcase : "tHIS IS cOMPUTERsCIENCE PERIOD"

RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------

Ex No: 7 Display the file content line by line


Date:

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

computer# science# practical#


hello# world#
enjoy# programming#

RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------

Ex No: 8 File Handling – read and write


Date:

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

lines that contain 'a' character are removed from result


Lines that contain 'a' character are added in result1

RESULT:

5 | MVM
Class: 12 CS PRACTICALS: 2024-25

The above program has been executed successfully.


-----------------------------------------------------------------------------------------------

Ex No: 9 File Handling – Read characters and store in separate file


Date:

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

Enter a single character :Y


Enter a single character :Z
Enter a single character :1
Enter a single character :2
Enter a single character :3
Enter a single character :4
Enter a single character :5
Enter a single character :6
Enter a single character :7
Enter a single character :8
Enter a single character :9
Enter a single character :!
Enter a single character :@
Enter a single character :#
Enter a single character :$
Enter a single character :%
Enter a single character :~
>>>

RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------

Ex No: 10 File Handling – Create Binary file for students details


Date:

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

Enter number of students :3


Enter roll no :1
Enter Name :anu
Enter marks :90
Enter roll no :2
Enter Name :abhi
Enter marks :96
Enter roll no :3
Enter Name :arun
Enter marks :97
Enter roll number :1
Enter new marks :92
Students marks updated successfully

RESULT:
The above program has been executed successfully.
-----------------------------------------------------------------------------------------------

Ex No: 12 File Handling - Create Binary file using dictionary

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.
-----------------------------------------------------------------------------------------------

Ex No: 13 File Handling - Create Binary file count records

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.
-----------------------------------------------------------------------------------------------

Ex No: 14 CSV file with Employee details and their Manipulations.

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'

with open('employee.csv', 'r') as csvfile:


myreader=csv.reader(csvfile, delimiter=',')
ans='y'
while ans.lower()=='y':
found=False
e=int(input("Enter Employee ID to search :"))
for row in myreader:
if len(row)!=0:
if int(row[0])==e:
print("Name :", row[1])
print("Mobile no: ", row[2])
found=True
break
if not found:
print("Employee ID not Found ")
ans=input("Do you want to search More? (y/n):")
ans='y'

with open('employee.csv', 'a') as csvfile:


x=csv.writer(csvfile)
x.writerow([eno,name,mobno ])

OUTPUT
Enter Employee ID :1
Enter Employee Name :aswath
Enter Employee Mobile No :9365550777

Do you want to Enter more data? (y/n):y


Enter Employee ID :2
Enter Employee Name :abhi
Enter Employee Mobile No :9635550888

Do you want to Enter more data? (y/n):y


Enter Employee ID :3
Enter Employee Name :arjun
Enter Employee Mobile No :9365550222

Do you want to Enter more data? (y/n):n


Enter Employee ID to search :2
Employee ID not Found
Name :arun
Mobile no: 9365550888

Do you want to search More? (y/n): n

RESULT:
The above program has been executed successfully.
---------------------------------------------------------------------------------------

11 | MVM
Class: 12 CS PRACTICALS: 2024-25

Ex No: 15 Stack using a list data


Date:

Write a python program to implement a stack using a list data – structure.

AIM: To implement a stack operation using a list data structure.

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

Enter your choice : 1


Enter integer value22
Enter your choice : 1
Enter integer value33
Enter your choice : 2
11
22
33
Enter your choice : 3
Deleted elements: 33
Enter your choice : 4
Peeked element: 22
Enter your choice : 1
11
22
Enter your choice :
RESULT:
The above program has been executed successfully.
---------------------------------------------------------------------------------------

Ex No: 16 SQL - Stationary and Consumer


Date:

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

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).
iii) To display the ConsumerName, Address from table Consumer and
company and price from table Stationery with their corresponding
matching S_ID.
iv) To increase the price of all Stationary by 2.
v) To display distinct Company from Stationary.

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

iii) To display the ConsumerName, Address from table Consumer and


company and price from table Stationery with their corresponding
matching S_ID.
iv) To increase the price of all Stationary by 2.
v) To display distinct Company from Stationary.

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);

create table CONSUMER (C_ID int, ConsumerName char(25), Address char(25),


S_ID char(5));
insert into CONSUMER values(01, “Good Learner”, “Delhi”, “PL01”);
insert into CONSUMER values(06, “Write Well”, “Mumbai”, “GP02”);
insert into CONSUMER values(12, “Topper”, “Delhi”, “DP01”);
insert into CONSUMER values(15, “Write & Draw”, “Delhi”, “PL02”);
insert into CONSUMER values(16, “Motivation”, “Banglore”, “PL01”);
OUTPUT:
i) Select * from consumer where Address=”Delhi”;

ii) Select * from stationary where price between 8 and 15;

iii) Select consumername.,address, company, price from


stationary,consumer where stationary.s_id=consumer.s_id;

iv) Update stationary set price=price +2;

Select * from stationary;

v) Select distinct(company) from stationary;

14 | MVM
Class: 12 CS PRACTICALS: 2024-25

RESULT:
The above program has been executed successfully.
---------------------------------------------------------------------------------------

Ex No: 17 SQL – ITEM AND TRADERS

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

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
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.

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”);

Create table TRADERS(TCode char(5), TName char(25), City char(20));

Insert into TRADERS Values(“T01”, “ELECTRONICS SALES”, “MUMBAI”);


Insert into TRADERS Values(“T03”, “BUSY STORE CORP”, “DELHI”);
Insert into TRADERS Values(“T02”, “DISP HOUSE INC”, “CHENNAI”);
OUTPUT:
i) Select * from ITEM order by IName;

ii) Select IName, Price from ITEM where Price between 10000 and 22000;

iii) Select TCode, count(*) from ITEM group by TCode;

iv) Select Price,IName,Qty from ITEM where Qty > 150;

v) Select TName from TRADERS where City in (“DELHI”, “MUMBAI”);

RESULT:
The above program has been executed successfully.
---------------------------------------------------------------------------------------

Ex No: 18 SQL – DOCTOR AND SALARY


Date:

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

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.

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

Insert into DOCTOR VALUES(109, “K George”, “MEDICINE”, “F”, 9);


Insert into DOCTOR VALUES(105, “Johnson”, “ORTHOPEDIC”, “M”, 10);
Insert into DOCTOR VALUES(117, “Lucy”, “ENT”, “F”, 3);
Insert into DOCTOR VALUES(111, “Bill”, “MEDICINE”, “F”, 12);
Insert into DOCTOR VALUES(130, “Morphy”, “ORTHOPEDIC”, “M”, 15);

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”;

iii) Select min(Allowance) from SALARY,DOCTOR where sex=’F’’ and


DOCTOR.ID =SALARY.ID;

iv) Select DOCTOR.ID, NAME,BASIC,ALLOWANCE from


DOCTOR,SALARY where DOCTOR.ID=SALARY.ID;

v) Select distinct(DEPT) from DOCTOR;

RESULT:
The above program has been executed successfully.
---------------------------------------------------------------------------------------

18 | MVM
Class: 12 CS PRACTICALS: 2024-25

Ex No: 19 SQL CONNECTIVITY : FETCH RECORD


Date:

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.
---------------------------------------------------------------------------------------

Ex No: 20 SQL CONNECTIVITY : COUNT RECORD


Date:

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.
---------------------------------------------------------------------------------------

Ex No: 21 SQL CONNECTIVITY : SEARCH RECORD


Date:

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.
---------------------------------------------------------------------------------------

Ex No: 22 SQL CONNECTIVITY : DELETE RECORD


Date:

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')]

RESULT: Thus the given program executed successfully.


-----------------------------------------------------------------------------------------------

21 | MVM

You might also like