Python Practical Record
Python Practical Record
SESSION 2023-24
1
CERTIFICATE
It is to be Certified that the ‘Practical Record’ submitted by Hasan
Mujtaba class 12th - A for the A.I.S.S.C.E. 2023-24 C.B.S.E.
Board Practical Examination in computer science, embodies the
original work done by the candidate. The candidate carried out his
work sincerely.
We have carefully gone through the contents of the project & are
fully satisfied with the work carried out by him,
Signature Signature
Mr. Gulshan Sharma Dr. Urmila Vajpai
( PGT Computer Science ) ( Principal )
2
Acknowledgement
Hasan Mujtaba
Class : 12th – A
Sacred Hearts School
3
Table of Content
def calculate(n):
if n <= 100 :
c = 500
elif n > 100 and n <= 200:
c = 500 + 2 * (n - 100)
elif n > 200 and n <= 300:
c = 500 + 2 * 100 + 4 * (n - 200)
else:
c = 500 + 2 * 100 + 4 * 100 + 6 * (n - 200)
return c
n = int (input("Enter Number of Units : "))
print("Electricity Bill : ", calculate(n))
6
PROGRAM 2 : Creating a nested Dictionary and searching a value
stu={}
per={}
n=int(input("Enter Number of Students : "))
for i in range(n):
r = int(input("Enter Roll Number : "))
n = input("Enter Name : ")
m = int(input("Enter Marks : "))
per['Name']=n
per['Marks']=m
stu[r]=dict(per)
print(stu)
ele = int(input("Enter roll no to be search : "))
for i in stu:
if ele == i:
print("Roll Number : ",i)
print("Name : ",stu[i]['Name'])
print("Marks : ",stu[i]['Marks'])
7
Enter Number of Students : 5
Enter Roll Number : 1
Enter Name : Raj
Enter Marks : 44
Enter Roll Number : 2
Enter Name : Deepak
Enter Marks : 22
Enter Roll Number : 3
Enter Name : Sumit
Enter Marks : 77
Enter Roll Number : 4
Enter Name : Mukesh
Enter Marks : 88
Enter Roll Number : 5
Enter Name : Rohit
Enter Marks : 77
{1: {'Name': 'Raj', 'Marks': 44}, 2: {'Name': 'Deepak', 'Marks': 22}, 3: {'Name': 'Sumit',
'Marks': 77}, 4: {'Name': 'Mukesh', 'Marks': 88}, 5: {'Name': 'Rohit', 'Marks': 77}}
Roll Number : 4
Name : Mukesh
Marks : 88
8
PROGRAM 4 : Traversal in a Linear List – manipulation of elements by dividing even
elements by 2 and multiplying other elements by 3
def show(a):
for i in range(len(a)):
if a[i] % 2 == 0:
a[i] = a[i] // 2
else:
a[i] = a[i] * 3
print("List after Modification : ", a)
#----------Main------------------
a = []
s = int(input("Enter Size of a List : "))
print("Enter element of the List")
for i in range(s):
a.append(int(input("Enter an element : ")))
print("Original List : ", a)
show(a)
Enter an element : 11
Enter an element : 22
Enter an element : 33
Enter an element : 44
Enter an element : 55
9
PROGRAM 5 : Traversal in a Linear List – displaying largest and smallest element of the
List
def show(a):
mx = mn = a[0]
for i in range(1, len(a)):
if a[i] > mx:
mx = a[i]
elif a[i] < mn:
mn = a[i]
print("Largest element is : " , mx)
print("Smallest element is : " , mn)
#----------Main------------------
a = []
s = int(input("Enter Size of a List : "))
print("Enter element of the List")
for i in range(s):
a.append(int(input("Enter an element : ")))
print("Original List : ", a)
show(a)
10
PROGRAM 6 : Traversal in a Linear List – reversing the elements of a List
def show(a):
for i in range(len(a)//2):
a[i], a[len(a)-1-i] = a[len(a)-1-i], a[i]
print("Reversed list is : " , a)
#----------Main------------------
a = []
s = int(input("Enter Size of a List : "))
print("Enter element of the List")
for i in range(s):
a.append(int(input("Enter an element : ")))
print("Original List : ", a)
show(a)
Output of the Program
:
Enter Size of a List : 6
Enter element of the List
Enter an element : 1
Enter an element : 2
Enter an element : 3
Enter an element : 4
Enter an element : 5
Enter an element : 6
11
PROGRAM 7 : Traversal in a Linear List – swapping of first half elements with next half
elements of a list
def show(a):
for i in range(len(a)//2):
a[i], a[len(a)//2+i] = a[len(a)//2+i], a[i]
print("Reversed list is : " , a)
#----------Main------------------
a = []
s = int(input("Enter Size of a List : "))
print("Enter element of the List")
for i in range(s):
a.append(int(input("Enter an element : ")))
print("Original List : ", a)
show(a)
12
PROGRAM 8 : Insertion in a Sorted Linear List
Enter an element : 10
Enter an element : 20
Enter an element : 30
Enter an element : 40
Enter an element : 50
Enter an element : 60
Enter an element : 70
13
PROGRAM 9 : Deletion of a given element in a Linear List
Enter an element : 10
Enter an element : 80
Enter an element : 30
Enter an element : 20
Enter an element : 90
Enter an element : 60
Enter an element : 50
14
PROGRAM 10 : Deletion of odd elements for a Linear List
def Deletion(a):
i = 0
while i <= len(a)-1:
if a[i]%2 == 0:
a.pop(i)
i+=1
print("List after Deletion : ", a)
#----------Main------------------
a = []
s = int(input("Enter Size of a List : "))
print("Enter element of the List")
for i in range(s):
a.append(int(input("Enter an element : ")))
print("Original List : ", a)
Deletion(a)
Enter an element : 5
Original List : [1, 2, 3, 4, 5]
List after Deletion : [1, 3, 5]
15
PROGRAM 11 : Merging of two Linear Lists
16
PROGRAM 12 : Merging of two Linear List in reverse order
17
PROGRAM 13 : Sorting a Linear List using Bubble Sort
def BubbleSort(a):
for i in range(len(a)):
for j in range(len(a)-1-i):
if a[j]>a[j+1]:
a[j] , a[j+1] = a[j+1] , a[j]
print(a)
#----------Main------------------
a = []
s = int(input("Enter Size of a List : "))
print("Enter element of the List")
for i in range(s):
a.append(int(input("Enter an element : ")))
BubbleSort("Sorted List is : ", a)
Enter an element : 5
Enter an element : 1
Enter an element : 4
Enter an element : 2
Enter an element : 8
18
PROGRAM 14 : Sorting a Linear List using Selection Sort
def SelectionSort(a):
for i in range(len(a)):
small = a[i]
p = i
for j in range(i+1, len(a)):
if a[j] < small:
small = a[j]
p = j
a[i], a[p] = a[p], a[i]
Enter an element : 64
Enter an element : 25
Enter an element : 12
Enter an element : 22
Enter an element : 11
19
PROGRAM 15 : Traversal in a Nested List – manipulation of elements
A = []
R = int(input("Enter No of Rows : "))
C = int(input("Enter No of Columns : "))
for i in range(R):
B = []
for j in range(C):
n=int(input("Enter an element : "))
B.append(n)
A.append(B)
20
Output of the Program :
Enter No of Rows : 3
Enter No of Columns : 3
Enter an element : 1
Enter an element : 2
Enter an element : 3
Enter an element : 4
Enter an element : 5
Enter an element : 6
Enter an element : 7
Enter an element : 8
Enter an element : 9
Original List is :
123
456
789
Modified List is :
319
2 15 3
21 4 27
21
PROGRAM 16 : Traversal in a Nested List – sum of even elements of a nested List
def show(A, R, C):
s = 0
for i in range(R):
for j in range(C):
if A[i][j] % 2 == 0:
s = s + A[i][j]
print("Sum of Even Elements : ", s)
A = []
R = int(input("Enter No of Rows : "))
C = int(input("Enter No of Columns : "))
for i in range(R):
B = []
for j in range(C):
n=int(input("Enter an element : "))
B.append(n)
A.append(B)
print("Original List is : ")
for i in range(R):
for j in range(C):
print(A[i][j], end = ' ')
print()
show(A, R, C)
Enter No of Rows : 3
Enter No of Columns : 3
Enter an element : 1
Enter an element : 2
Enter an element : 3
Enter an element : 4
Enter an element : 5
Enter an element : 6
Enter an element : 7
Enter an element : 8
Enter an element : 9
Original List is :
123
456
789
Sum of Even Elements : 20
22
PROGRAM 17 : Nested List – displaying elements of upper right triangle in a square matrix
def show(A, R, C):
for i in range(R):
for j in range(C):
if i <= j:
print(A[i][j], end = ' ')
else :
print(' ', end = ' ')
print()
A = []
R = int(input("Enter No of Rows : "))
C = int(input("Enter No of Columns : "))
for i in range(R):
B = []
for j in range(C):
n=int(input("Enter an element : "))
B.append(n)
A.append(B)
23
PROGRAM 18 : Nested List – displaying elements of middle row and column of a square
matrix
def show(A, R, C):
for i in range(R):
for j in range(C):
if i == R//2 or j == C//2:
print(A[i][j], end = ' ')
else :
print(' ', end = ' ')
print()
A = []
R = int(input("Enter No of Rows : "))
C = int(input("Enter No of Columns : "))
for i in range(R):
B = []
for j in range(C):
n=int(input("Enter an element : "))
B.append(n)
A.append(B)
24
PROGRAM 19 : Nested List – displaying elements of both the diagonals in a square matrix
def show(A, R, C):
for i in range(R):
for j in range(C):
if i == j or i + j == C-1:
print(A[i][j], end = ' ')
else :
print(' ', end = ' ')
print()
A = []
R = int(input("Enter No of Rows : "))
C = int(input("Enter No of Columns : "))
for i in range(R):
B = []
for j in range(C):
n=int(input("Enter an element : "))
B.append(n)
A.append(B)
Enter No of Rows : 3
Enter No of Columns : 3
Enter an element : 1
Enter an element : 2
Enter an element : 3
Enter an element : 4
Enter an element : 5
Enter an element : 6
Enter an element : 7
Enter an element : 8
Enter an element : 9
Original List is :
123
456
789
Both the Diagonals of List :
1 3
5
7 9
25
PROGRAM 20 : Nested List – displaying elements present on the boundary of a square
matrix
def show(A, R, C):
for i in range(R):
for j in range(C):
if i == 0 or i == R-1 or j == 0 or j == C-1:
print(A[i][j], end = ' ')
else :
print(' ', end = ' ')
print()
A = []
R = int(input("Enter No of Rows : "))
C = int(input("Enter No of Columns : "))
for i in range(R):
B = []
for j in range(C):
n=int(input("Enter an element : "))
B.append(n)
A.append(B)
print("Original List is : ")
for i in range(R):
for j in range(C):
print(A[i][j], end = ' ')
print()
print("Boundary elements of List : ")
show(A, R, C)
Output of the Program :
Enter No of Rows : 3
Enter No of Columns : 3
Enter an element : 1
Enter an element : 2
Enter an element : 3
Enter an element : 4
Enter an element : 5
Enter an element : 6
Enter an element : 7
Enter an element : 8
Enter an element : 9
Original List is :
123
456
789
Boundary elements of List :
123
4 6
789
26
PROGRAM 21 : Nested List – transpose of a square matrix
def show(A, R, C):
for i in range(R):
for j in range(C):
if i <= j:
A[i][j], A[j][i] = A[j][i], A[i][j]
for i in range(R):
for j in range(C):
print(A[i][j], end = ' ')
print()
A = []
R = int(input("Enter No of Rows : "))
C = int(input("Enter No of Columns : "))
for i in range(R):
B = []
for j in range(C):
n=int(input("Enter an element : "))
B.append(n)
A.append(B)
print("Original List is : ")
for i in range(R):
for j in range(C):
print(A[i][j], end = ' ')
print()
print("Transpose of List : ")
show(A, R, C)
Output of the Program :
Enter No of Rows : 3
Enter No of Columns : 3
Enter an element : 1
Enter an element : 2
Enter an element : 3
Enter an element : 4
Enter an element : 5
Enter an element : 6
Enter an element : 7
Enter an element : 8
Enter an element : 9
Original List is :
123
456
789
Transpose of List :
147
258
369
27
PROGRAM 22 : Implementing a Stack using a List
def Push(a):
ele = int(input("Enter an element to be inserted in Stack : "))
a.append(ele)
def Pop(a):
if a == []:
print("Underflow")
else:
print("Popped element is : ", a.pop())
def Peek(a):
if a == []:
print("Underflow")
else:
print("element at the top : ", a[len(a)-1])
def Display(a):
if a == []:
print("Underflow")
else:
for i in range(len(a)-1,-1,-1):
print(a[i])
#-------------------------------MAIN--------------------------------
--
a = []
top = None
while True:
print("Stack Operatons")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
ch = int(input("Enter Choice : "))
if ch == 1:
Push(a)
elif ch == 2:
Pop(a)
elif ch == 3:
Peek(a)
elif ch == 4:
Display(a)
elif ch == 5:
break
28
Output of the Program :
Enter Choice : 4
88
33
66
29
PROGRAM 23 : Text File – Writing and Reading data
30
PROGRAM 24 : Searching characters in a text file
def abc():
file=open('data.txt','r')
content =file.read()
print(content)
x=y=z=0
for i in content:
if i.isupper():
x+=1
if i.islower():
y+=1
else:
z+=1
print ("No. of Upper Case Characters are : ", x)
print ("No. of Lower Case Characters are : ", y)
print ("No. of OtherCharacters are : ", z)
file.close()
abc()
31
PROGRAM 25 : Searching words in a text file
def abc():
x = 0
file=open('data.txt','r')
data=file.readlines()
for line in data:
print(line)
word = line.split()
for i in word:
if i == 'is':
x+=1
file.close()
print("is counted : ", x)
abc()
32
PROGRAM 26 : Searching lines in a text file – display the line which contains ‘Second’ as
sub-string.
def abc():
file=open('data.txt','r')
data=file.readlines()
for line in data:
if 'Second' in line:
print(line)
file.close()
abc()
def abc():
file=open('data.txt','r')
content =file.read()
print(content)
print()
for i in content:
if i == 'T':
print('C', end = '')
else:
print(i, end = '')
file.close()
abc()
33
PROGRAM 28 : Deletion in a text file – delete the word ‘This’
def abc():
file=open('data.txt','r')
content =file.read()
word = content.split()
b = ''
for i in word:
if i != 'This':
b = b +' '+ i
file.close()
file=open('data.txt','w')
file.write(b)
file.close()
file=open('data.txt','r')
content =file.read()
print(content)
file.close()
abc()
34
PROGRAM 29 : Binary File – Writing and Reading data of a dictionary having names of
three students.
import pickle
def writing():
n = {1:'ram',2:'mohan', 3:'shyam'}
file = open('bylist.dat', 'wb')
pickle.dump(n,file)
print("Data added successfully")
file.close()
def reading():
file = open('bylist.dat', 'rb')
n = pickle.load(file)
print(n)
file.close()
writing()
reading()
35
PROGRAM 30 : Searching data in a binary file. Writing data of student in the form of
dictionary and displaying records of those students who are having marks greater than 90.
import pickle
def writing():
s = int(input("Enter Number of Students : "))
file = open('bylist.dat', 'wb')
d ={}
for i in range(s):
r = int(input("Enter Roll No : "))
n = input("Enter Name :")
m = int(input("Enter Marks : "))
d['rollno']=r
d['name']=n
d['marks']=m
pickle.dump(d,file)
print("Data added successfully")
file.close()
def reading():
file = open('bylist.dat', 'rb')
try:
while True:
d = pickle.load(file)
if d['marks']>90:
print(d)
except EOFError :
file.close()
writing()
reading()
36
Output of the Program :
Enter Roll No : 1
Enter Marks : 95
Enter Roll No : 2
Enter Marks : 34
Enter Roll No : 3
Enter Marks : 93
37
PROGRAM 31 : Write a menu driven program to implement WRITING, READING,
SEARCHING, MODIFICATION and DELETION in a binary file “data.dat” using a Dictionary to
store the data. Let us create following functions to implement the above mentioned task :
1) Create a binary file “data.dat” containing records of a student in the form of a
Dictionary with keys ‘rollno’, ‘name’, ‘marks’ and ‘grade’ and write it in the file.
2) Display the records of all the students from the binary file “data.dat”.
3) Search and display the records of the students from the binary file “data.dat” whose
name is given by the user.
4) Modify the content of the binary file “data.dat” by increasing the marks of the
students by 5 whose roll no is given by user.
SOLUTION:
import pickle
def writingdata():
file = open('data.dat', 'ab')
a = int(input('Enter Roll Number : '))
b = input('Enter Name : ')
c = int(input('Enter Marks : '))
d = input('Enter Grade : ')
ob = {'rollno':a, 'name':b, 'marks':c, 'grade':d}
pickle.dump(ob, file)
file.close()
def displaydata():
file = open('data.dat', 'rb')
try:
while True:
ob = pickle.load(file)
print('Roll Number : ', ob['rollno'])
print('Name : ', ob['name'])
print('Marks : ', ob['marks'])
print('Grade : ', ob['grade'])
except EOFError:
file.close()
def searchdata():
file = open('data.dat', 'rb')
try:
n = input('Enter name to be search : ')
f = 0
while True:
ob = pickle.load(file)
if ob['name'] == n:
f = 1
print('Roll Number : ', ob['rollno'])
print('Name : ', ob['name'])
print('Marks : ', ob['marks'])
print('Grade : ', ob['grade'])
except EOFError:
38
file.close()
if f == 0:
print('Record not found for this name')
def modifydata():
file = open('data.dat', 'rb+')
try:
n = int(input('Enter roll number to be modify : '))
f = 0
while True:
p = file.tell()
ob = pickle.load(file)
if ob['rollno'] == n:
f = 1
ob['marks'] = ob['marks'] + 5
file.seek(p)
pickle.dump(ob, file)
except EOFError:
file.close()
if f == 0:
print('No record found for this roll number')
#--------------Main Program-------------------
ch = ' '
while ch != '0':
print('Press 1 for Insertion')
print('Press 2 for Display')
print('Press 3 for Searching')
print('Press 4 for Modification')
print('Press 5 for Deletion')
print('press 0 for Exit')
ch = input('Enter your choice : ')
if ch == '1':
writingdata()
elif ch == '2':
displaydata()
elif ch == '3':
searchdata()
elif ch == '4':
modifydata()
elif ch == '0':
break
else:
print('Inter a valid choice')
39
PROGRAM 32 : You are required to write a menu driven program to implement WRITING,
READING, and SEARCHING in a CSV file “records.csv” using a List to store the data. Let us
create following functions to implement the above mentioned task :
1) Create a CSV file “records.csv” containing records of a student [RollNumber, Name,
Marks, Grade] in the form of a list and write it in the file.
2) Display the records of all the students from the CSV file “records.csv”.
3) Search and display the records of the students from the CSV file “records.csv” whose
name is given by the user.
Solution:
import csv
def writedata():
file = open('records.csv', 'a', newline='')
ob = csv.writer(file)
a = int(input('Enter Roll Number : '))
b = input('Enter Name : ')
c = int(input('Enter Marks : '))
d = input('Enter Grade : ')
L = [a, b, c, d]
ob.writerow(L)
file.close()
def displaydata():
file = open('records.csv', 'r')
ob = csv.reader(file)
for i in ob:
print('Roll Number : ', i[0])
print('Name : ', i[1])
print('Marks : ', i[2])
print('Grade : ', i[3])
file.close()
def searchdata():
file = open('records.csv', 'r')
ob = csv.reader(file)
nm = input('Enter name to be search : ')
f = 0
for i in ob:
if i[1] == nm:
f = 1
print('Roll Number : ', i[0])
print('Name : ', i[1])
print('Marks : ', i[2])
print('Grade : ', i[3])
file.close()
if f == 0:
print('Record no found for this name')
40
#--------------Main Program-------------------
ch = ' '
while ch != '0':
print('Press 1 for Insertion')
print('Press 2 for Display')
print('Press 3 for Searching')
print('press 0 for Exit')
ch = input('Enter your choice : ')
if ch == '1':
writingdata()
elif ch == '2':
displaydata()
elif ch == '3':
searchdata()
elif ch == '0':
break
else:
print('Inter a valid choice')
41
42
Consider the following tables and write SQL commands for the given statements
1) Table : PRODUCT
P_ID ProductName Manufacturer Price
TP01 Talcom Powder LAK 40
FW05 Face Wash ABC 45
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ 95
Table : CLIENT
C_ID ClientName City P_ID
01 Cosmetic Shop Delhi FW05
06 Total Health Mumbai BS01
12 Live Life Delhi SH06
12 Pretty Woman Delhi FW12
16 Dreams Banglore TP01
Answers
1) Select * from CLIENT where City = ‘Delhi’;
2) Select * from PRODUCT where Price between 50 and 100;
3) Select ClientName, City, ProductName, Price from CLIENT A , PRODUCT B where A . P_ID
= B . P_ID;
4) Update PRODUCT set Price = Price + 10 where Manufacturer = ‘ABC’ ;
a. Count ( Distinct City)
3
b. Manufacturer Max ( Price )
LAK 40
ABC 55
XYZ 120
c. ClientName Manufacturer
Cosmatic Shop ABC
Total Health ABC
Live Life XYZ
Pretty Woman XYZ
Dreams LAK
d. ProductName Price * 4
Talcom Powder 160
Face Wash 180
Bath Soap 220
Shampoo 480
Face Wash 380
43
2) Table : Emp
Empid Firstname Lastname Address City
010 Ravi Kumar Raj nagar GZB
152 Sam Tones 33 Elm St. Paris
215 Sarah Ackerman 440 U.S. 110 Upton
244 Manila Sengupta 24 Friends street New Delhi
300 Robert Samuel 9 Fifth Cross Washington
335 Ritu Tondon Shastri Nagar GZB
400 Rachel Lee 121 Harrison St. New York
Sal
Empid Salary Benefits Designation
010 75000 15000 Manager
152 80000 25000 Director
215 75000 12500 Manager
244 50000 12000 Clerk
300 45000 10000 Clerk
335 40000 10000 Clerk
400 32000 7500 Salesman
(i) To show firstname, address and city of all employees living in Paris
(ii) To display the content of Employees table having empid > 200 in descending order of Firstname.
(iii) To display the firstname and total salary of all managers from the tables Emp and sal , where total
salary is calculated as salary+benefits.
(iv) To display the maximum salary among managers and clerks from the table sal.
(v) Give the Output of following SQL commands:
(i) Select count(distinct designation) from sal;
(ii) Select designation, Count(*) from sal group by designation having count(*) >2;
(iii) Select sum(benefits) from sal where designation =’Clerk’;
(iv) Select distinct City from Emp;
Answers
a) Select Firstname, Address from Emp where City = ‘Paris’;
b) Select * from Emp where Empid > 200 Order By Firstname Desc;
c) Select Firstname, Salary + Benefits “Total Salary” from Emp A, Sal B Where A . Empid = B .
Empid and Designation = ‘Manager’;
d) Select Max ( Salary ) from Sal where Designation In (‘Manager’ , ‘Clerk’);
I. Count(distinct designation)
4
44
3) Table : ITEM
I_ID ItemName Manufacturer Price
PC01 Personal Computer ABC 35000
LC05 Laptop ABC 55000
PC03 Personal Computer XYZ 32000
PC06 Personal Computer COMP 37000
LC03 Laptop PQR 57000
Table : CUSTOMER
C_ID CustomerName City I_ID
01 N Roy Delhi LC03
06 H Singh Mumbai PC03
12 R Pandey Delhi PC06
15 C Sharma Delhi LC03
16 K Agarwal Banglore PC01
Answers
1) Select * from CUSTOMER where City = ‘Delhi’;
h. ItemName Price * 10
Personal Computer 350000
Laptop 550000
45
4) 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
117 Lucy ENT F 3
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
a) Display Name of all doctors who are in ‘MEDICINE’ having more than 10 years experience.
b) Display the Salary of all doctors working in ‘ENT’ department, where Salary = Basic + Allowance.
c) Display the minimum Allowance of female doctors.
d) Increase the Basic Salary of the doctors by 10% whose consultation fees is greater than 200.
e) Give output :
i) Select Count(*) from Doctor where sex = ‘F’;
ii) Select Name, Basic From Doctor, Sal Where Dept = ‘ENT’ And Doctor.ID = Salary.ID;
iii) Select Distinct Dept from Doctor where Sex = ‘M’;
iv) Select Sum(Consultation) from Doctor, Sal where Doctor.ID = Salary.ID and Experience >= 10;
Answers
a) Select Name from Doctor where Dept = ‘MEDICINE’ and Experience > 10;
b) Select Basic + Allowance “ Salary “ from Doctor A , Sal B where A . ID = B . ID and Dept = ‘ENT’;
c) Select Min ( Allowance ) from Doctor A, Sal B Where A . ID = B . ID and Sex = ‘F’;
c) Update Sal set Basic = Basic + 0.1 * Basic where Consultation > 200 ;
i. Count( * )
3
46
5) Table : Voter
a) To display the information of Voters who live in Delhi and having age in between 30 and 50.
b) Create a view “VIP” having information of male Voters who belong to Area “Civil Lines”.
c) Display Name and Age of male Voters whose name starts with ‘A’ in the descending order of there
Age and alphabetical order of their Name.
d) Display average Age of the male Voters of each city.
e) Assign the value of age as 18 to those Voters whose age is NULL.
f) Insert a new row in the table Voter with following values ( 108 , ‘Neha’ , ‘Old City’ , ‘Bareilly’ , ‘F’ ,
36).
Answers
a) Select * from Voter where City = ‘Delhi’ and Age Between 30 and 50;
b) Create View VIP as Select * from Voter where Area = ‘Civil Lines’ and Sex = ‘M’;
c) Select Name , Age from Voter where Sex = ‘F’ and Name Like ‘A%’ Order By Age Desc, Name ;
d) Select Avg ( Age ) from Voter Group By City Having Sex = ‘M’ ;
f) Insert Into Voter Values ( 108 , ‘Neha’ , ‘Old City’ , ‘Bareilly’ , ‘F’ , 36);
47
Integrating MySQL with Python
1) Write a Python database connectivity script that will insert a record in the table
STUDENT ( ID , NAME , CLASS , MARKS , GRADE) with following values (007, ‘James
Bond’, 12, 100, ‘A’ ). Use following details to establish the connection of MySQL database
with a Python applicaion:
Host Name – “localhost” , User Name – “root” , Password – “pass” , Database –
“SCHOOL”
Solution:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user =
"root", password = "pass", database = "SCHOOL")
cursor = conobj.cursor()
st = "Insert into STUDENT(ID, NAME, CLASS, MARKS, GRADE) Values
(007, 'James Bond', 12, 100, 'A' )"
cursor.execute(st)
conobj.commit()
conobj.close()
2) Write a Python database connectivity script that will display all the records of the
table STUDENT by reading them one by one from the table.
Solution:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user =
"root", password = "pass", database = "SCHOOL")
cursor = conobj.cursor()
st = "Select * From STUDENT"
cursor.execute(st)
data = cursor.fetchone()
while data is not None:
print(data)
data = cursor.fetchone()
conobj.close()
3) Write a Python database connectivity script that will display the records of those
students who are having grade ‘A’ or ‘B’ from the table STUDENT.
Solution:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user =
"root", password = "pass", database = "SCHOOL")
cursor = conobj.cursor()
st = "Select * From STUDENT Where Grade In ('A', 'B')"
cursor.execute(st)
data = cursor.fetchall()
print(data)
conobj.close()
48
4) Write a Python database connectivity script that will update the table STUDENT by
assigning the grade as ‘A’ to those students who are having marks in the range of 90 and
100.
Solution:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user =
"root", password = "pass", database = "SCHOOL")
cursor = conobj.cursor()
st = "Update STUDENT Set Grade = 'A' Where Marks Between 90 and
100"
cursor.execute(st)
conobj.commit()
conobj.close()
5) Write a Python database connectivity script that will update the table STUDENT by
increasing the marks by 5 to those students who are having grade ‘C’. After update
display all the records from the table.
Solution:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user =
"root", password = "pass", database = "SCHOOL")
cursor = conobj.cursor()
st = "Update STUDENT Set Marks = Marks + 5 Where Grade = 'C'"
cursor.execute(st)
conobj.commit()
st = "Select * From STUDENT"
cursor.execute(st)
data = cursor.fetchall()
for i in data:
print(i)
conobj.close()
6) Write a Python database connectivity script that will delete the records of the
students who are having marks less than 40 or grade as ‘C’ from the table STUDENT.
Solution:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user =
"root", password = "pass", database = "SCHOOL")
cursor = conobj.cursor()
st = "Delete From STUDENT Where Marks < 40 or Grade = 'C'"
cursor.execute(st)
conobj.commit()
conobj.close()
49
7) Write a Python database connectivity script that will read Id, name, class, marks and
grade from user and insert the records in the STUDENT table.
Solution:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user =
"root", password = "pass", database = "SCHOOL")
cursor = conobj.cursor()
a = int(input('Enter ID : '))
b = input('Enter Name : ')
c = int(input('Enter Class : '))
d = int(input('Enter Marks : '))
e = input('Enter Grade : ')
st = "Insert into STUDENT(ID, NAME, CLASS, MARKS, GRADE)
Values({}, '{}', {}, {}, '{}')".format(a,b,c,d,e)
cursor.execute(st)
conobj.commit()
conobj.close()
8) Write a Python database connectivity script that will read class and grade from user
and display the details of the student for the same.
Solution:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user =
"root", password = "pass", database = "SCHOOL")
cursor = conobj.cursor()
a = int(input('Enter Class : '))
b = input('Enter Grade : ')
st = "Select * From STUDENT Where Class = {} and Grade =
'{}'".format(a, b)
cursor.execute(st)
data = cursor.fetchall()
print(data)
conobj.close()
50
9) Write a Python database connectivity script that will read name and marks from user
and update the details of the student whose name is given by the user by assigning the
marks with the given value.
Solution:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user =
"root", password = "pass", database = "SCHOOL")
cursor = conobj.cursor()
a = input('Enter Name : ')
b = int(input('Enter Marks : '))
st = "Update STUDENT Set Marks = {} Where Name = '{}'".format(a,
b)
cursor.execute(st)
conobj.commit()
conobj.close()
10) Write a Python database connectivity script that will read marks from user and
delete the records of those students who are having marks below the given marks.
Solution:
import mysql.connector
conobj = mysql.connector.connect(host = "localhost", user =
"root", password = "pass", database = "SCHOOL")
cursor = conobj.cursor()
a = int(input('Enter Marks : '))
st = "Delete From STUDENT Where Marks < {}".format(a)
cursor.execute(st)
conobj.commit()
conobj.close()
51