Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
36 views

Python Practical Record

The document contains a practical record submitted by Hasan Mujtaba of class 12th A to his computer science teacher, which includes certificates signed by the teacher and principal verifying the original work, an acknowledgement thanking those who helped, and a table of contents listing 30 programming problems and their solutions.

Uploaded by

Hasan Mujtaba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Python Practical Record

The document contains a practical record submitted by Hasan Mujtaba of class 12th A to his computer science teacher, which includes certificates signed by the teacher and principal verifying the original work, an acknowledgement thanking those who helped, and a table of contents listing 30 programming problems and their solutions.

Uploaded by

Hasan Mujtaba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

PRACTICAL RECORD

SESSION 2023-24

SUBMITTED BY: SUBMITTED TO:

Hasan Mujtaba Mr. Gulshan Sharma

(XII-A) (P.G.T Computer Science)

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,

It is further certified that the candidate has completed all the


prescribed requirements governing the syllabus of C.B.S.E. Sr. Sec
Board.

Signature Signature
Mr. Gulshan Sharma Dr. Urmila Vajpai
( PGT Computer Science ) ( Principal )

2
Acknowledgement

In the 'odyssey' of 'life' the reverie to subjugate the zenith of


goal to many known & unknown hands obtrude me learnt
souls put me on right path & enlightened with their
knowledge & experience. I shall ever remain grateful to them.
Words are inadequate to express my sincere & deepest sense of
gratitude to my guide & teacher Mr. Gulshan Sharma for his
benevolent guidance, constructive counsel, & meticulous
supervision, constant inspirations & wholehearted
encouragement throughout the year.

At last I shall heartily thank to my parents &


for their love, care, concern & lots of inspirations.

Hasan Mujtaba
Class : 12th – A
Sacred Hearts School

3
Table of Content

Sr. No. Topic


1 Function to calculate electricity bill on the bases of number of units
2 Creating a nested Dictionary and searching a value
3 Traversal in a Linear List – manipulation of elements
4 Traversal in a Linear List – displaying largest and smallest element of the List
5 Traversal in a Linear List – reversing the elements of a List
6 Traversal in a Linear List – swapping of the elements
7 Insertion in a Sorted Linear List
8 Deletion of a given element in a Linear List
9 Deletion of odd elements for a Linear List
10 Merging of two Linear Lists
11 Merging of two Linear List in reverse order
12 Sorting a Linear List using Bubble Sort
13 Sorting a Linear List using Selection Sort
14 Traversal in a Nested List – manipulation of elements
15 Traversal in a Nested List – sum of even elements of a nested List
16 Nested List – displaying elements of upper right triangle in a square matrix
17 Nested List – displaying elements of middle row and column of a square matrix
18 Nested List – displaying elements of both the diagonals in a square matrix
19 Nested List – displaying elements present on the boundary of a square matrix
20 Nested List – transpose of a square matrix
21 Implementing a Stack using a List
22 Implementing a Queue using a List
23 Text File – Writing and Reading data
24 Searching characters in a text file
25 Searching words in a text file
26 Searching lines in a text file
27 Modification in a text file
28 Processing Binary File
29 Processing CSV file
30 Problem of SQL – Queries
31 Python Connectivity Script with MySQL Database
4
5
PROGRAM 1 : Read number of units from user and calculate the electricity bill as follows–
Units Charges
<=100 500
>100 and <=200 2 per extra unit over 100
>200 and <=300 4 per extra unit over 200
>300 6 per extra unit over 300

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

Output of the Program :

Enter Number of Units : 320

Electricity Bill : 1820

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

Output of the Program :

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

Enter roll no to be search : 4

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)

Output of the Program :

Enter Size of a List : 5

Enter element of the List

Enter an element : 11

Enter an element : 22

Enter an element : 33

Enter an element : 44

Enter an element : 55

Original List : [11, 22, 33, 44, 55]

List after Modification : [33, 11, 99, 22, 165]

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)

Output of the Program :

Enter Size of a List : 6


Enter element of the List
Enter an element : 44
Enter an element : 11
Enter an element : 77
Enter an element : 44
Enter an element : 99
Enter an element : 22

Original List : [44, 11, 77, 44, 99, 22]


Largest element is : 99
Smallest element is : 11

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

Original List : [1, 2, 3, 4, 5, 6]


Reversed list is : [6, 5, 4, 3, 2, 1]

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)

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

Original List : [1, 2, 3, 4, 5, 6]


Reversed list is : [4, 5, 6, 1, 2, 3]

12
PROGRAM 8 : Insertion in a Sorted Linear List

def Insertion(a, ele):


p = -1
for i in range(len(a)):
if ele < a[i]:
p = i
break
if p == -1 :
a.append(ele)
else:
a.insert(p,ele)
print("List after Insertion : ", 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 : ")))
ele = int(input("Enter element to be inserted : "))
print("Original List : ", a)
Insertion(a, ele)

Output of the Program :

Enter Size of a List : 7


Enter element of the 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

Enter element to be inserted : 25

Original List : [10, 20, 30, 40, 50, 60, 70]


List after Insertion : [10, 20, 25, 30, 40, 50, 60, 70]

13
PROGRAM 9 : Deletion of a given element in a Linear List

def Deletion(a, ele):


p = -1 #default position in case element not present
for i in range(len(a)):
if ele == a[i]:
p = i
break
a.pop(p)
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 : ")))
ele = int(input("Enter element to be deleted : "))
print("Original List : ", a)
Deletion(a, ele)

Output of the Program :

Enter Size of a List : 7


Enter element of the 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

Enter element to be deleted : 30

Original List : [10, 80, 30, 20, 90, 60, 50]


List after Deletion : [10, 80, 20, 90, 60, 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)

Output of the Program :

Enter Size of a List : 5


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
Original List : [1, 2, 3, 4, 5]
List after Deletion : [1, 3, 5]

15
PROGRAM 11 : Merging of two Linear Lists

def Merging(a, b):


c = a + b
print("First List : ", a)
print("Second List : ", b)
print("Merged List : ", c)
#----------Main------------------
a = []
b = []
s = int(input("Enter Size of first List : "))
print("Enter element of First List")
for i in range(s):
a.append(int(input("Enter an element : ")))
s = int(input("Enter Size of Second List : "))
print("Enter element of Second List")
for i in range(s):
b.append(int(input("Enter an element : ")))
Merging(a, b)

Output of the Program :

Enter Size of first List : 3


Enter element of First List
Enter an element : 55
Enter an element : 22
Enter an element : 44

Enter Size of Second List : 4


Enter element of Second List
Enter an element : 99
Enter an element : 66
Enter an element : 88
Enter an element : 77

First List : [55, 22, 44]


Second List : [99, 66, 88, 77]
Merged List : [55, 22, 44, 99, 66, 88, 77]

16
PROGRAM 12 : Merging of two Linear List in reverse order

def Merging(a, b):


a.reverse()
b.reverse()
c = a +b
print("First List : ", a)
print("Second List : ", b)
print("Merged List : ", c)
#----------Main------------------
a = []
b = []
s = int(input("Enter Size of first List : "))
print("Enter element of First List")
for i in range(s):
a.append(int(input("Enter an element : ")))
s = int(input("Enter Size of Second List : "))
print("Enter element of Second List")
for i in range(s):
b.append(int(input("Enter an element : ")))
Merging(a, b)

Output of the Program :

Enter Size of first List : 3


Enter element of First List
Enter an element : 1
Enter an element : 2
Enter an element : 3

Enter Size of Second List : 4


Enter element of Second List
Enter an element : 9
Enter an element : 8
Enter an element : 7
Enter an element : 6

First List : [3, 2, 1]


Second List : [6, 7, 8, 9]
Merged List : [3, 2, 1, 6, 7, 8, 9]

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)

Output of the Program :

Enter Size of a List : 5


Enter element of the List

Enter an element : 5
Enter an element : 1
Enter an element : 4
Enter an element : 2
Enter an element : 8

Sorted List is : [1, 2, 4, 5, 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]

print("Sorted 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 : ")))
SelectionSort(a)

Output of the Program :

Enter Size of a List : 5


Enter element of the List

Enter an element : 64
Enter an element : 25
Enter an element : 12
Enter an element : 22
Enter an element : 11

Sorted List is : [11, 12, 22, 25, 64]

19
PROGRAM 15 : Traversal in a Nested List – manipulation of elements

def show(A, R, C):


for i in range(R):
for j in range(C):
if A[i][j] % 2 == 0:
A[i][j] = A[i][j] // 2
else:
A[i][j] = A[i][j] * 3

print("Modified List is : ")


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()
show(A, R, C)

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)

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

print("Original List is : ")


for i in range(R):
for j in range(C):
print(A[i][j], end = ' ')
print()
print("Upper Right Triangle 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
Upper Right Triangle of List :
123
56
9

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)

print("Original List is : ")


for i in range(R):
for j in range(C):
print(A[i][j], end = ' ')
print()
print("Middle Row and Column 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
Middle Row and Column of List :
2
456
8

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)

print("Original List is : ")


for i in range(R):
for j in range(C):
print(A[i][j], end = ' ')
print()
print("Both the Diagonals 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
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 :

Stack Operatons Stack Operatons


1. Push 1. Push
2. Pop 2. Pop
3. Peek 3. Peek
4. Display 4. Display
5. Exit 5. Exit

Enter Choice : 1 Enter Choice : 2


Popped element is : 88
Enter an element to be inserted in Stack : 66 Stack Operatons
Stack Operatons 1. Push
1. Push 2. Pop
2. Pop 3. Peek
3. Peek 4. Display
4. Display 5. Exit
5. Exit
Enter Choice : 4
Enter Choice : 1 33
66
Enter an element to be inserted in Stack : 33 Stack Operatons
Stack Operatons 1. Push
1. Push 2. Pop
2. Pop 3. Peek
3. Peek 4. Display
4. Display 5. Exit
5. Exit
Enter Choice : 3
Enter Choice : 1 element at the top : 33
Stack Operatons
Enter an element to be inserted in Stack : 88 1. Push
Stack Operatons 2. Pop
1. Push 3. Peek
2. Pop 4. Display
3. Peek 5. Exit
4. Display
5. Exit Enter Choice : 5

Enter Choice : 4
88
33
66

29
PROGRAM 23 : Text File – Writing and Reading data

File = open("record.txt", "w")


for i in range(4):
n = input("Enter a Line : ")
n = n + '\n'
File.write(n)
File.close()
print("Data writing is successful")

print(“Data Present in File”)


file = open("record.txt", "r")
data = file.read()
print(data)
file.close()

Output of the Program :

Enter a Line : This is First line


Enter a Line : This is Second line
Enter a Line : This is Third line
Enter a Line : This is Forth line

Data writing is successful

Data Present in File

This is First line


This is Second line
This is Third line
This is Forth line

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

Output of the Program :

This is First line


This is Second line
This is Third line
This is Forth line

No. of Upper Case Characters are : 8


No. of Lower Case Characters are : 53
No. of OtherCharacters are : 23

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

Output of the Program :

This is First line


This is Second line
This is Third line
This is Forth line
is counted : 4

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

Output of the Program :

This is Second line

PROGRAM 27 : Modification in a text file – display the character ‘T’ as ‘C’

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

Output of the Program :

This is First line


This is Second line
This is Third line
This is Forth line

Chis is First line


Chis is Second line
Chis is Chird line
Chis is Forth line

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

Output of the Program :

is First line is Second line is Third line is Forth line

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

Output of the Program :

Data added successfully

{1: 'ram', 2: 'mohan', 3: 'shyam'}

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 Number of Students : 3

Enter Roll No : 1

Enter Name :Raj

Enter Marks : 95

Enter Roll No : 2

Enter Name :Dinesh

Enter Marks : 34

Enter Roll No : 3

Enter Name :Ravi

Enter Marks : 93

Data added successfully

{'rollno': 1, 'name': 'Raj', 'marks': 95}

{'rollno': 3, 'name': 'Ravi', '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

1) To display the details of those Clients whose City is Delhi.


2) To display the details of products whose Price is in the range of 50 to 100 ( Both values included ).
3) To display the ClientName, City from table CLIENT and ProductName and Price from table
PRODUCT, with their corresponding matching P_ID.
4) To increase the price of all Products by 10 which are having Manufacturer ABC.
5) Give outputs:
a. select Count ( distinct City ) from Client;
b. select Manufacturer, MAX (Price) from Product Group By Manufacturer;
c. select ClientName, Manufacturer from Client, Product where Client . P_ID = Product . P_ID;
d. select ProductName, Price * 4 from Product;

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

II. Designation Count(*)


Clerk 3

III. Sum ( Benefits )


32000

IV. Distinct city


GZB
Paris
Upton
New Delhi
Washington
New York

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

a) To display the details of those customers whose city is Delhi.


b) To display the details of Item whose Price is in the range of 35000 to 55000 (Both values included).
c) To display CustomerName, City, ItemName and Price of those items whose price is more than 50000.
d) To increase the Price of all items by 1000 in the table Item.
e) Give output of the following commands:
i) Select Count(Distinct City) From Customer;
ii) Select ItemName, Max(Price)) From Item Group By ItemName;
iii) Select CustomerName, Manufacturer From Item, Customer
Where Item . I_ID = Customer . I_I_D;
iv) Select ItemName, Price * 100 From Item Where Manufacturer = ‘ABC’;

Answers
1) Select * from CUSTOMER where City = ‘Delhi’;

2) Select * from ITEM where Price between 35000 and 55000;

3) Select CustomerName, City, ItemName, Price from CUSTOMER A , ITEM B where A .


I_ID = B . I_ID;

4) Update ITEM set Price = Price + 10 ;

e. Count ( Distinct City)


3
f. ItemName Max ( Price )
ABC 55000
XYZ 32000
COMP 37000
PQR 57000
g. CustomerName Manufacturer
N Roy PQR
H Singh XYZ
R Pandey COMP
C Sharma PQR
K Agarwal ABC

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

ii. Designation Basic


John 12000

iii. Min ( Allowance )


1700

iv. Sum ( Consultation )


800

46
5) Table : Voter

VoterID Name Area City Sex Age


101 Ravi Sanjay Nagar Bareilly M 45
102 Seema Ram Nagar Delhi F 35
103 Alex Central Point Delhi M 25
104 Nitin Pawan Bihar Bareilly M 42
105 Sudha Avadh Avas Mumbai F 55
106 Pushpa Civil Lines Delhi F 33
107 Ali Old City Bareilly M 40

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

e) Update Voter Set Age = 18 Where Age Is Null;

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

You might also like