0% found this document useful (0 votes)
11 views18 pages

0_Practical--2023 - 24

The document outlines practical exercises for Class 12 Computer Science, detailing various Python programming tasks including list and tuple manipulation, dictionary updates, string functions, file handling, and random number generation. Each exercise includes an aim, program code, and expected output. The document confirms successful execution of each program.
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)
11 views18 pages

0_Practical--2023 - 24

The document outlines practical exercises for Class 12 Computer Science, detailing various Python programming tasks including list and tuple manipulation, dictionary updates, string functions, file handling, and random number generation. Each exercise includes an aim, program code, and expected output. The document confirms successful execution of each program.
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/ 18

Class: 12 CS PRACTICALS: 2022-23

Ex No: 1 List
Ex No: 2 Tuple
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 2. Write a Python program input n numbers in tuple and pass it
element after changing. to function to count how many even and odd numbers are
entered.
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 AIM: To write a program to input n numbers in tuple and pass it to
changing . function to count how many even and odd numbers are entered.

SOFTWARE USED: IDLE (PYTHON 3.8 64-bit) SOFTWARE USED : IDLE (PYTHON 3.8 64-bit)

PROGRAM CODE:
PROGRAM CODE:
def fun(lst):
def fun(lst): eve=0
list2=[ ] odd=0
for i in range(0, len(lst)): for i in range(0, len(lst)):
if(lst[i]%2==0): if lst[i]%2 == 0:
eve =lst[i]/2 eve+=1
list2.append(eve) else:
else: odd+=1
eve=lst[i]*2 print("Number of even numbers :", eve, "Number of odd numbers :",
list2.append(eve) odd)
print(list2)
x=eval(input("Enter a tuple :"))
a=eval(input("Enter a list :")) fun(x)
fun(a)
OUTPUT
OUTPUT: Enter a tuple :(1,2,3,4,5,6,7)
Number of even numbers : 3 Number of odd numbers : 4
Enter a list :[1,2,3,4,5]
[2, 1.0, 6, 2.0, 10] RESULT:
The above program has been executed successfully.
RESULT: -----------------------------------------------------------------------------------------------
The above program has been executed successfully. Ex No: 3 Dictionary
-----------------------------------------------------------------------------------------------
3. Write a Python program to function with key and value, and
update value at that key in dictionary entered by user.
1 | MVM
Class: 12 CS PRACTICALS: 2022-23

RESULT:
AIM:To write a program to function with key and value, and update The above program has been executed successfully.
value at that key in dictionary entered by user. -----------------------------------------------------------------------------------------------

SOFTWARE USED: IDLE (PYTHON 3.8 64-BIT) Ex No: 4 Count vowels in String

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


PROGRAM CODE: count how many vowels present in the string.

def fun(d,k): AIM:To write a program to pass a string to a function and count how
value2=eval (input("Enter the value :")) many vowels present in the string.
d[k]=value2
print ("Updated dictionary :", d) SOFTWARE USED : IDLE (PYTHON 3.8 64-BIT)
x=int (input ("Number of pairs in dictionary :"))
dic={ }
for i in range(x): PROGRAM CODE :
key = eval (input ("Enter the key :"))
value = eval(input ("Enter the value :")) def fun(lst):
dic[key]=value count = 0
print ("Original dictionary :", dic) for i in range (0, len(lst)):
a= eval(input("Enter the key whose value you want to change :")) if lst[i]=="a" or lst[i]=="A":
fun (dic, a) count+=1
if lst[i]=="e" or lst[i]=="E":
count+=1
OUTPUT if lst[i]=="i" or lst[i]=="I":
count+=1
Number of pairs in dictionary :3 if lst[i]=="o" or lst[i]=="O":
Enter the key :"name" count+=1
Enter the value :"sanjay" if lst[i]=="u" or lst[i]=="U":
Enter the key :"age" count+=1
Enter the value :"15" print("Number of vowels :", count)
Enter the key :"class" a=eval(input("Enter a String :"))
Enter the value :"10" fun(a)
Original dictionary : {'name': 'sanjay', 'age': '15', 'class': '10'}
Enter the key whose value you want to change :"age" OUTPUT
Enter the value :16
Updated dictionary : {'name': 'sanjay', 'age': 16, 'class': '10'} Enter a String :"computer Science"
Number of vowels : 6
RESULT:

2 | MVM
Class: 12 CS PRACTICALS: 2022-23

The above program has been executed successfully.


---------------------------------------------------------------------------------------------- PROGRAM CODE:
c=str(input(" Enter sentence: "))
Ex No: 5 Generate Random Numbers a=input("Enter the spacing :")
print("The string entered is a word : ", c.isalpha())
5. Write a Python program to generator (Random Number) that print("The string entered is lower case : ", c.lower())
generates random numbers between 1 and 6 (simulates a dice) print("The string entered is in lower case : ", c.islower())
using user defined function. print("The string entered is upper case : ", c.upper())
print("The string entered is in upper case : ", c.isupper())
AIM:To write a program to generator that generates random numbers print("The string entered after removing the space from left side : ",
between 1 and 6 using user defined function. c.lstrip())
print("The string entered after removing the space from right side : ",
SOFTWARE USED: IDLE (PYTHON 3.8 64-BIT) c.rstrip())
print("The string entered contains whitespace :", c.isspace())
INPUT print("The string entered is titlecased :", c.istitle())
print("The string entered after joining with ", a, ":", a.join(c))
def fun(): print("The string entered after swaping case : ", c.swapcase())
import random
r=random.randint(1,6)
print("Random numbers generated between 1 to 6 :", r) OUTPUT
fun()
Enter sentence: "This is Computer Science period"
OUTOUT Enter the spacing :--
Random numbers generated between 1 to 6 : 5 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
RESULT: The string entered is upper case : "THIS IS COMPUTER SCIENCE
The above program has been executed successfully. PERIOD"
----------------------------------------------------------------------------------------------- The string entered is in upper case : False
The string entered after removing the space from left side : "This is
Computer Science period"
Ex No: 6 String Functions The string entered after removing the space from right side : "This is
Computer Science period"
6. Write a python program to implement python string functions. The string entered contains whitespace : False
The string entered is titlecased : False
AIM: To write a program to implement python string functions. 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--"
SOFTWARE USED: IDLE (PYTHON 3.8 64-BIT) The string entered after swapingcase : "tHIS IS cOMPUTERsCIENCE
PERIOD"

3 | MVM
Class: 12 CS PRACTICALS: 2022-23

8. Write a python program to remove all the lines that contain the
RESULT: character ‘a’ in a file and write it to another file.
The above program has been executed successfully.
----------------------------------------------------------------------------------------------- AIM:To write a program to remove all the lines that contain the
character ‘a’ in a file and write it to another file.
Ex No: 7 Display the file content line by line
SOFTWARE USED- IDLE (PYTHON 3.8 64-BIT)
7. Write a python program to read and display file content line by line
with each word separated by #. PROGRAM CODE:
AIM : To write a program to read and display file content line by line file=open(r"f:\result.txt", "r")
with each word separated by #. lines=file.readlines()
file.close()
SOFTWARE USED: IDLE (PYTHON 3.8 64-BIT) file=open(r"f:\result.txt", "w")
file1=open(r"f:\result1.txt", "w")
PROGRAM CODE: for li in lines:
if 'a' in li:
a= open(r"f:\result.txt", "r") file1.write(li)
lines=a.readlines() else:
for le in lines: file.write(li)
x=le.split() print("lines that contain 'a' character are removed from result")
for y in x: print ("Lines that contain 'a' character are added in result1 ")
print(y+ "#", end=" ") file.close()
print(" ") file1.close()

OUTPUT OUTPUT

computer# science# practical#


hello# world# lines that contain 'a' character are removed from result
enjoy# programming# Lines that contain 'a' character are added in result1

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

Ex No: 8 File Handling – read and write

4 | MVM
Class: 12 CS PRACTICALS: 2022-23

f1.write(c)
elif c.isupper():
f2.write(c)
else:
f3.write(c)
f1.close()
f2.close()
f3.close()

OUTPUT
RESULT:
Input "`" to stop execution.
The above program has been executed successfully.
Enter a single character :a
-----------------------------------------------------------------------------------------------
Enter a single character :b
Enter a single character :c
Ex No: 9 File Handling – Read characters and store in separate Enter a single character :d
file Enter a single character :e
Enter a single character :f
9. Write a python program to read characters from keyboard one by Enter a single character :g
one, all lower case letters gets stored inside a file “LOWER”, all Enter a single character :h
uppercase letters gets stored inside a file “UPPER”, and all other Enter a single character :i
characters get stored inside “OTHERS” 3 Enter a single character :j
Enter a single character :k
AIM: To write a program to read characters from keyboard one by one, Enter a single character :l
all lower case letters gets stored inside a file “LOWER”, all uppercase Enter a single character :M
letters gets stored inside a file “UPPER”, and all other characters get Enter a single character :N
stored inside “OTHERS” Enter a single character :O
Enter a single character :P
SOFTWARE USED- IDLE (PYTHON 3.8 64-bit) Enter a single character :Q
Enter a single character :R
INPUT Enter a single character :S
f1=open(r"f:\lower.txt",'w') Enter a single character :T
f2=open(r"f:\upper.txt",'w') Enter a single character :U
f3=open(r"f:\others.txt",'w') Enter a single character :V
print('Input "`" to stop execution. ') Enter a single character :W
while True: Enter a single character :X
c=input("Enter a single character :") Enter a single character :Y
if c=="~": Enter a single character :Z
break Enter a single character :1
elif c.islower(): Enter a single character :2

5 | MVM
Class: 12 CS PRACTICALS: 2022-23

Enter a single character :3 sdata={ }


Enter a single character :4 slist=[]
Enter a single character :5 total=int(input("Enter number of students : "))
Enter a single character :6 for i in range(total):
Enter a single character :7 sdata["Roll no:"]=int(input("Enter Roll no : "))
Enter a single character :8 sdata["Name :"]=input("Enter Name :")
Enter a single character :9 slist.append(sdata)
Enter a single character :! sdata={ }
Enter a single character :@ a=open(r"f:\text.dat", "wb")
Enter a single character :# pickle.dump(slist, a)
Enter a single character :$ a.close()
Enter a single character :%
Enter a single character :~ x=open(r"f:text.dat", "rb")
>>> slist=pickle.load(x)
b=int(input("Enter the roll number of student to be searched :"))
y=False
for text in slist:
if(text["Roll no:"]==b):
y=True
print(text["Name :"], "Found in file")
if(y==False):
RESULT: print("Data of student not found :")
The above program has been executed successfully.
----------------------------------------------------------------------------------------------- OUTPUT 1:
Enter number of students : 3
Ex No: 10 File Handling – Create Binary file for students details
Enter Roll no : 1
Enter Name :hema
10. Write a python program to create a binary file with name and roll
Enter Roll no : 2
number. Search for a given roll number and display name, if not
Enter Name :arun
found display appropriate message.
Enter Roll no : 3
Enter Name :archana
AIM: To write a program to create a binary file with name and roll
Enter the roll number of student to be searched :5
number, search for a given roll number and display name, if not Data of student not found :
found display appropriate.
SOFTWARE USED: IDLE (PYTHON 3.8 64-BIT)
OUTPUT 2:
Enter number of students : 3
PROGRAM CODE: Enter Roll no : 1
Enter Name :hema
import pickle Enter Roll no : 2

6 | MVM
Class: 12 CS PRACTICALS: 2022-23

Enter Name :arun a=open(r"f:\bin.dat", "rb+")


Enter Roll no : 3 try:
Enter Name :anu while True:
Enter the roll number of student to be searched :3 pos=a.tell()
anu Found in file sdata=pickle.load(a)
if (sdata["Roll no"]==rollno):
RESULT: sdata["Marks"]=float(input("Enter new marks :"))
The above program has been executed successfully. a.seek(pos)
---------------------------------------------------------------------------------------------- pickle.dump(sdata, a)
found=True
Ex No: 11 File Handling - Create Binary file for students except EOFError:
details and update the details if found==False:
print("Roll number not found ")
11. Write a python program to create a binary file with roll number, else:
name and marks, input a roll number and update the marks. print("Students marks updated successfully")
a.close()
AIM:To write a program to create a binary file with roll number, name
and marks, input a roll number and update the marks.
OUTPUT
SOFTWARE USED- IDLE (PYTHON 3.8 64-bit)
Enter number of students :3
PROGRAM CODE: Enter roll no :1
Enter Name :anu
import pickle Enter marks :90
sdata={ } Enter roll no :2
total=int(input("Enter number of students :")) Enter Name :abhi
a=open(r"f:\bin.dat", "wb") Enter marks :96
for i in range(total): Enter roll no :3
sdata["Roll no"]=int (input("Enter roll no :")) Enter Name :arun
sdata["Name"]=input("Enter Name :") Enter marks :97
sdata ["Marks"]=float(input("Enter marks :")) Enter roll number :1
pickle.dump(sdata,a) Enter new marks :92
sdata={ } Students marks updated successfully
a.close()
RESULT:
#updating marks The above program has been executed successfully.
-----------------------------------------------------------------------------------------------
found=False
rollno=int(input("Enter roll number :")) Ex No: 12 File Handling - Create Binary file using dictionary

7 | MVM
Class: 12 CS PRACTICALS: 2022-23

AIM:To Write a function to count records from the binary file


12. Write a program to store customer data into a binary file cust.dat marks.dat.
using a dictionary and print them on screen after reading them. The
customer data contains ID as key, and name, city as values.
SOFTWARE USED- IDLE (PYTHON 3.8 64-bit)
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 PROGRAM CODE:
them. The customer data contains ID as key, and name, city as
values. import pickle
def count_records():
SOFTWARE USED- IDLE (PYTHON 3.8 64-bit) f = open("cust.dat","rb")
cnt=0
PROGRAM CODE: try:
while True:
import pickle data = pickle.load(f)
def bin2dict(): for s in data:
f = open("cust.dat","wb") cnt+=1
d = {'C0001':['Subham','Ahmedabad'], except Exception:
'C0002':['Bhavin','Anand'], f.close()
'C0003':['Chintu','Baroda']} print("The file has ", cnt, " records.")
pickle.dump(d,f) count_records()
f.close() OUTPUT:
f = open("cust.dat","rb") The file has 3 records.
d = pickle.load(f)
print(d) RESULT:
f.close() The above program has been executed successfully.
bin2dict() -----------------------------------------------------------------------------------------------

OUTPUT:
{'C0001': ['Subham', 'Ahmedabad'], 'C0002': ['Bhavin', 'Anand'], Ex No: 14 CSV file with Employee details and their
'C0003': ['Chintu', 'Baroda']} Manipulations.

RESULT: 14. Write a python program to create a CSV file with empid, name and
The above program has been executed successfully. mobile no. and search empid, update the record and display the
----------------------------------------------------------------------------------------------- records.
Ex No: 13 File Handling - Create Binary file count records
AIM: To write a program to create a CSV file with empid, name and
13. Write a function to count records from the binary file marks.dat. mobile no. and search empid, update the record and display the
records.

8 | MVM
Class: 12 CS PRACTICALS: 2022-23

SOFTWARE USED- IDLE (PYTHON 3.8 64-BIT) OUTPUT


Enter Employee ID :1
PROGRAM CODE: Enter Employee Name :aswath
Enter Employee Mobile No :9365550777
import csv
Do you want to Enter more data? (y/n):y
with open('employee.csv', 'a') as csvfile: Enter Employee ID :2
mywriter=csv.writer(csvfile, delimiter=',') Enter Employee Name :abhi
ans='y' Enter Employee Mobile No :9635550888
while ans.lower()=='y':
eno=int(input("Enter Employee ID :")) Do you want to Enter more data? (y/n):y
name=input("Enter Employee Name :") Enter Employee ID :3
mobno=int(input("Enter Employee Mobile No :")) Enter Employee Name :arjun
mywriter.writerow([eno, name, mobno]) Enter Employee Mobile No :9365550222
ans=input("Do you want to Enter more data? (y/n):")
ans='y' Do you want to Enter more data? (y/n):n
Enter Employee ID to search :2
with open('employee.csv', 'r') as csvfile: Employee ID not Found
myreader=csv.reader(csvfile, delimiter=',') Name :arun
ans='y' Mobile no: 9365550888
while ans.lower()=='y':
found=False Do you want to search More? (y/n): n
e=int(input("Enter Employee ID to search :"))
for row in myreader: RESULT:
if len(row)!=0: The above program has been executed successfully.
if int(row[0])==e: ---------------------------------------------------------------------------------------
print("Name :", row[1])
print("Mobile no: ", row[2])
found=True
break Ex No: 15 Stack using a list data
if not found: Write a python program to implement a stack using a list data –
print("Employee ID not Found ") structure.
ans=input("Do you want to search More? (y/n):")
ans='y' AIM: To implement a stack operation using a list data structure.
with open('employee.csv', 'a') as csvfile: PROGRAM CODE:
x=csv.writer(csvfile)
x.writerow([eno,name,mobno ]) stack =[]

9 | MVM
Class: 12 CS PRACTICALS: 2022-23

def view(): peek()


for x in range (len(stack)): else:
print(stack[x]) print("Wrong choice")
OUTPUT:
def push(): Stack operation
item=int(input("Enter integer value")) ****************
stack.append(item) 1. View
2. Push
def pop(): 3. Pop
if(stack==[]): 4. Peek
print("Stack is empty") Enter your choice : 2
else: Enter integer value11
item=stack.pop(-1) Enter your choice : 2
print("Deleted elements:", item) Enter integer value22
Enter your choice : 2
def peek(): Enter integer value33
item=stack[-1] Enter your choice : 1
print("Peeked element:", item) 11
22
print("Stack operation") 33
print("****************") Enter your choice : 3
print("1. View ") Deleted elements: 33
print("2. Push ") Enter your choice : 4
print("3. Pop ") Peeked element: 22
print("4. Peek ") Enter your choice : 1
while True: 11
choice=int(input("Enter your choice : ")) 22
if choice==1: Enter your choice :
view() RESULT:
elif choice==2: The above program has been executed successfully.
push() ---------------------------------------------------------------------------------------
elif choice==3:
pop() Ex No: 16 SQL - Stationary and Consumer
elif choice==4:

10 | MVM
Class: 12 CS PRACTICALS: 2022-23

Create two tables for stationary and consumer and execute the given ii) To display the details of Stationary whose Price is in the
commands using SQL. range of 8 to 15 (Both values included).
Table: Stationary iii) To display the ConsumerName, Address from table
S_ID StationaryName Company Price Consumer and company and price from table Stationery with
their corresponding matching S_ID.
DP01 Dot Pen ABC 10 iv) To increase the price of all Stationary by 2.
PL02 Pencil XYZ 6 v) To display distinct Company from Stationary.
ER05 Eraser XYZ 7
PL01 Pencil CAM 5 PROGRAM CODE:
GP02 Gel Pen ABC 15 Create table stationary(S_ID char(5) not null primary key,
stationaryname char(25), company char(5), price int);
Table: Consumer insert into stationary values("DP01","Dot pen","ABC",10);
C_ID ConsumerName Address S_ID insert into stationary values("PL02","Pencil","XYZ",6);
insert into stationary values("ER05","Eraser","XYZ",7);
01 Good Learner Delhi PL01 insert into stationary values("PL01","Pencil","CAM",5);
06 Write Well Mumbai GP02 insert into stationary values("GP02","Gel pen","ABC",15);
12 Topper Delhi DP01
15 Write & Draw Delhi PL02 create table CONSUMER (C_ID int, ConsumerName char(25), Address
16 Motivation Bangalore PL01 char(25), S_ID char(5));
insert into CONSUMER values(01, “Good Learner”, “Delhi”, “PL01”);
i) To display the details of those Consumers whose Address is insert into CONSUMER values(06, “Write Well”, “Mumbai”, “GP02”);
Delhi. insert into CONSUMER values(12, “Topper”, “Delhi”, “DP01”);
ii) To display the details of Stationary whose Price is in the insert into CONSUMER values(15, “Write & Draw”, “Delhi”, “PL02”);
range of 8 to 15 (Both values included). insert into CONSUMER values(16, “Motivation”, “Banglore”, “PL01”);
iii) To display the ConsumerName, Address from table
OUTPUT:
Consumer and company and price from table Stationery with
i) Select * from consumer where Address=”Delhi”;
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. ii) Select * from stationary where price between 8 and 15;
i) To display the details of those Consumers whose Address is
Delhi.

11 | MVM
Class: 12 CS PRACTICALS: 2022-23

iii) Select consumername.,address, company, price from Table: Item


stationary,consumer where stationary.s_id=consumer.s_id;
Code IName Qt Price Compan TCo
y y de
1001 Digital Pad 12 11000 XENTIA T01
121 0
1006 LED Screen 70 38000 SANTOR T02
40 A
iv) Update stationary set price=price +2; 1004 Car Gps 50 2150 GEOKNO T01
System W
Select * from stationary; 1003 Digital 16 8000 DIGICLI T02
Camera 12X 0 CK
1005 Pen Drive 60 1200 STOREH T03
32GB 0 OME
Table: Traders
TCode TName City
T01 Electronics Sales Mumbai
T03 Busy Store Corp Delhi
v) Select distinct(company) from stationary; 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).
RESULT: iii) To display the number of items, which are traded by each
The above program has been executed successfully. trader. The expected output of this query should be
--------------------------------------------------------------------------------------- T01 2
T02 2
Ex No: 17 SQL – ITEM AND TRADERS T03 1
iv) To display the price, item name (i.e. IName) and quantity (i.e.
1) Create two tables for item and traders and execute the given Qty) of those items which have quantity more than 150.
commands using SQL. v) To display the name of those traders, who are either from
Delhi or from Mumbai.

12 | MVM
Class: 12 CS PRACTICALS: 2022-23

Insert into TRADERS Values(“T01”, “ELECTRONICS SALES”,


“MUMBAI”);
AIM: To Create two tables for item and traders and execute the given Insert into TRADERS Values(“T03”, “BUSY STORE CORP”, “DELHI”);
commands using SQL. Insert into TRADERS Values(“T02”, “DISP HOUSE INC”, “CHENNAI”);
i) To display the details of all the items in ascending order of OUTPUT:
item names (i.e. IName). i) Select * from ITEM order by 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 ii) Select IName, Price from ITEM where Price between 10000
T02 2 and 22000;
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. iii) Select TCode, count(*) from ITEM group by TCode;
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”); iv) Select Price,IName,Qty from ITEM where Qty > 150;
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, v) Select TName from TRADERS where City in (“DELHI”,
“DIGICLICK”,”T02”); “MUMBAI”);
Insert into Item values(1005, “PEN DRIVE 32GB”, 600, 12000,
“STOREHOME”,”T03”);

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


RESULT:

13 | MVM
Class: 12 CS PRACTICALS: 2022-23

The above program has been executed successfully. 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.

Ex No: 18 SQL – DOCTOR AND SALARY


Create two tables for Doctor and Salary and execute the given ID Name Dept Sex Experience
commands using SQL.
101 John ENT M 12
Table: Doctor
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
Table: Salary
111 Bill MEDICINE F 12
ID Basic Allowance Consultation
130 Morphy ORTHOPEDIC M 15
101 12000 1000 300 AIM: To Create two tables for Doctor and Salary and execute the given
104 23000 2300 500 commands using SQL.
107 32000 4000 500 i) To display Name of all doctors who are in “Medicine” having
114 12000 5200 100 more than 10 years experience from table Doctor.
109 42000 1700 200 ii) To display the average salary of all Doctors working in “ENT”
105 18900 1690 300 department using the tables Doctor and Salary (Salary =
130 21700 2600 300 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.
i) To display Name of all doctors who are in “Medicine” having
PROGRAM CODE:
more than 10 years experience from table Doctor.
Create Table DOCTOR(ID int not null primary key, Name char(25),
ii) To display the average salary of all Doctors working in “ENT”
department using the tables Doctor and Salary (Salary = Dept char(25), sex char, Experience int);
Basic + Allowance). Insert into DOCTOR VALUES(101, “John”, “ENT”, “M”, 12);
iii) To display minimum Allowance of female doctors. Insert into DOCTOR VALUES(104, “Smith”, “ORTHOPEDIC”, “M”, 5);
Insert into DOCTOR VALUES(107, “George”, “CARDIOLOGY”, “M”,
10);
14 | MVM
Class: 12 CS PRACTICALS: 2022-23

Insert into DOCTOR VALUES(114, “Lara”, “SKIN”, “F”, 3);


Insert into DOCTOR VALUES(109, “K George”, “MEDICINE”, “F”, 9);
Insert into DOCTOR VALUES(105, “Johnson”, “ORTHOPEDIC”, “M”,
10);
iv) Select DOCTOR.ID, NAME,BASIC,ALLOWANCE from
Insert into DOCTOR VALUES(117, “Lucy”, “ENT”, “F”, 3);
DOCTOR,SALARY where DOCTOR.ID=SALARY.ID;
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); v) Select distinct(DEPT) from DOCTOR;
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);
RESULT:
OUTPUT:
The above program has been executed successfully.
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;

15 | MVM
Class: 12 CS PRACTICALS: 2022-23

Ex No: 20 SQL CONNECTIVITY : COUNT RECORD

Ex No: 19 SQL CONNECTIVITY : FETCH RECORD 20. Write a python program (integrate python with SQL) to count
19. Write a python program (integrate python with SQL) to fetch the records from table.
records from table.
AIM: To write a python program (integrate python with SQL) to count
AIM: To write a python program (integrate python with SQL) to fetch records from table.
the records from table.
Program code:
PROGRAM CODE: import mysql.connector as sqltor
import mysql.connector as sqltor mycon=sqltor.connect(host="localhost",
mycon=sqltor.connect(host="localhost", user="root",password="1234",database="trinity")
if mycon.is_connected()==False:
user="root",password="1234",database="trinity") print("Error connecting to Mysql database")
if mycon.is_connected()==False: cursor=mycon.cursor()
print("Error connecting to Mysql database") cursor.execute("select * from student")
cursor=mycon.cursor() data=cursor.fetchone()
cursor.execute("select * from student") count=cursor.rowcount
data=cursor.fetchall() print("Total number of rows retrieved from resultset : ", count)
count=cursor.rowcount data=cursor.fetchone()
for row in data: count=cursor.rowcount
print(row)
print("Total number of rows retrieved from resultset : ", count)
mycon.close() data=cursor.fetchmany(3)
count=cursor.rowcount
OUTPUT: print("Total number of rows retrieved from resultset : ", count)
(1001, 'Arun', 23, 34, 45, 50, 44, 'Coimbatore') mycon.close()
(1002, 'Abhishek', 44, 50, 45, 35, 50, 'Coimbatore')
(1002, 'Swarna', 47, 50, 35, 39, 50, 'Coimbatore') OUTPUT:
Total number of rows retrieved from resultset : 1
RESULT: Total number of rows retrieved from resultset : 2
The above program has been executed successfully.
Total number of rows retrieved from resultset : 3
---------------------------------------------------------------------------------------

16 | MVM
Class: 12 CS PRACTICALS: 2022-23

RESULT: The above program has been executed successfully.


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

Ex No: 21 SQL CONNECTIVITY : SEARCH RECORD Ex No: 22 SQL CONNECTIVITY : DELETE RECORD

21. Wrie a python program (integrate python with SQL) to search the 22. Write a python program (integrate python with SQL) to delete the
records from table. records from table.

AIM: To write a python program (integrate python with SQL) to search AIM : To write a python program (integrate python with SQL) to delete
the records from table. the records from table.

PROGRAM CODE: PROGRAM CODE:


import mysql.connector as mc import mysql.connector as mc
mycon=mc.connect(host="localhost",user="root",password="1234",dat mycon=mc.connect(host="localhost",user="root",password="1234",dat
abase="db12") abase="db12")
if mycon.is_connected(): if mycon.is_connected():
print("py->sql connected") print("py->sql connected")
eno=int(input("Enter num: ")) eno=int(input("Enter num: "))
mcursor=mycon.cursor() mcursor=mycon.cursor()
mcursor.execute("select * from emp") mcursor.execute("select * from emp")
allrow=mcursor.fetchall() allrow=mcursor.fetchall()
for row in allrow: for row in allrow:
if row[0]==eno: if row[0]==eno:
print(row) mcursor.execute("delete from emp where eno={}".format(eno))
mycon.commit() mcursor.execute("select * from emp")
mycon.close() print(mcursor.fetchall())

OUTPUT: mycon.commit()
py->sql connected mycon.close()
Enter num: 102
(102, 'abhishek', 35, 'coimbatore') OUTPUT:
py->sql connected
RESULT: Enter num: 101

17 | MVM
Class: 12 CS PRACTICALS: 2022-23

[(102, 'abhishek', 35, 'coimbatore'), (103, 'aashikk', 38, 'coimbatore')]

RESULT: Thus the given program executed successfully.


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

18 | MVM

You might also like