0% found this document useful (0 votes)
5 views50 pages

Python Programs for Area, String, and File Operations

The document contains a series of practical Python programming exercises that cover various concepts such as calculating areas of shapes, counting characters in strings, managing stacks, file operations, and manipulating binary files. Each practical includes code snippets, expected outputs, and explanations of the functionality. The exercises aim to enhance understanding of Python programming through hands-on implementation.

Uploaded by

simransrivastava
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)
5 views50 pages

Python Programs for Area, String, and File Operations

The document contains a series of practical Python programming exercises that cover various concepts such as calculating areas of shapes, counting characters in strings, managing stacks, file operations, and manipulating binary files. Each practical includes code snippets, expected outputs, and explanations of the functionality. The exercises aim to enhance understanding of Python programming through hands-on implementation.

Uploaded by

simransrivastava
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

PRACTICAL – 1

Write Python program to calculate area of square, rectangle,


triangle and circle by using user defined functions.
def area_of_square(L):
print("Area of square=",L**2)
def area_of_rectangle(L,B):
print("Area of rectangle=",L*B)
def area_of_triangle(B,H):
print("Area of triangle=",1/2*B*H)
def area_of_circle(R):
print("Area of circle=",3.14*R**2)
length=int(input("Enter length of square and rectangle:"))
breadth=int(input("Enter breadth of rectangle:"))
b=int(input("Enter base of triangle:"))
h=int(input("Enter height of triangle:"))
r=int(input("Enter radius of circle:"))
area_of_square(length)
area_of_triangle(b,h)
area_of_rectangle(length,breadth)
area_of_circle(r)
Output:
Enter length of square and rectangle:5
Enter breadth of rectangle:10
Enter base of triangle:20
Enter height of triangle:15
Enter radius of circle:7
Area of square= 25
Area of triangle= 150.0
Area of rectangle= 50
Area of circle= 153.86

1
PRACTICAL – 2
Write Python program to count total uppercase and lowercase
letters, digits and special characters (along with space) present in
inputted string by using user defined number.
def String_count(s):
uc,lc,digit,sc=0,0,0,0
for i in s:
if [Link]():
uc=uc+1
elif [Link]():
lc=lc+1
elif [Link]():
digit=digit+1
else:
sc=sc+1
print("Total uppercase characters=",uc)
print("Total lowercase characters=",lc)
print("Total digit characters=",digit)
print("Total special characters=",sc)
s1=input('Enter string:')
String_count(s1)
Output:
Enter string:Computer Science Python 2023
Total uppercase characters= 3
Total lowercase characters= 18
Total digit characters= 4
Total special characters= 3

2
PRACTICAL – 3
Write Python program to display maximum value from list without
using max() by using concept of user defined function.
def maximum(L):
m=L[0]
for i in L:
if m<i:
m=i
print(m)
List=eval(input("Enter list to find maximum value:"))
maximum(List)

Output:
Enter list to find maximum value: [-5.23,-5.95,-5.05,-5.99]
-5.05

3
PRACTICAL – 4
Write Python program to find length of list or tuple by using user
defined function. List or Tuple must be inputted by user.
def Length(L):
count=0
for i in L:
print(i,end='\t')
count=count+1
print()
print("Total values present in List/Tuple=",count)
L1=eval(input("Enter list or tuple:"))
Length(L1)

Output:
Enter list or tuple:(5,10,15,20)
5 10 15 20
Total values present in List/Tuple= 4

4
PRACTICAL – 5
Write Python program to implement the concept of stack by using
push and pop operations.

def push(L):
global top
top=top+1
v=int(input("Enter any integer value:"))
[Link](top,v)
def pop(L):
global top
if top==-1:
print("Stack is already empty")
else:
t=[Link](top)
print("Deleted value:",t)
top=top-1
L=[]
top=-1
D={1:'Insert value into stack(Push)',2:'Delete value from
stack(Pop)','Others':'Exit'}
while True:
for i,j in [Link]():
print(i,j,sep='\t')
c=int(input("Enter your choice:"))
if c==1:

5
push(L)
elif c==2:
pop(L)
else:
print("Invalid option. Stack is over")
break
print("Current stack:",L)
Output:
1 Insert value into stack(Push)
2 Delete value from stack(Pop)
Others Exit

Enter your choice:2


Stack is already empty
Current stack: []
1 Insert value into stack(Push)
2 Delete value from stack(Pop)
Others Exit

Enter your choice:1

Enter any integer value:5


Current stack: [5]
1 Insert value into stack(Push)
2 Delete value from stack(Pop)
Others Exit

Enter your choice:1

Enter any integer value:10


6
Current stack: [5, 10]
1 Insert value into stack(Push)
2 Delete value from stack(Pop)
Others Exit

Enter your choice:1

Enter any integer value:15


Current stack: [5, 10, 15]
1 Insert value into stack(Push)
2 Delete value from stack(Pop)
Others Exit

Enter your choice:2


Deleted value: 15
Current stack: [5, 10]
1 Insert value into stack(Push)
2 Delete value from stack(Pop)
Others Exit

Enter your choice:2


Deleted value: 10
Current stack: [5]
1 Insert value into stack(Push)
2 Delete value from stack(Pop)
Others Exit

Enter your choice:3


Invalid option. Stack is over

7
PRACTICAL – 6
Create a text file named [Link] by writing multiple lines and read
that text file line by line and display each word separated by a #.

f=open("D:\\[Link]","w+")
[Link](["SCIENCE HAS COMPUTER SCIENCE.\n",
"Think good ,be good ,do good.\n",
"COMMERCE HAS INFORMATICS PRACTICES.\n",
"science and commerce both have physical education.1234\n",
"I like computer science.\n",
"Believe in Yourself."])
[Link](0)
s=[Link]()
while s!='':
for i in s:
if i==' ':
print('#',end='')
else:
print(i,end='')
s=[Link]()
[Link]()

Output:-
SCIENCE#HAS#COMPUTER#SCIENCE.
Think#good#,be#good#,do#good.
COMMERCE#HAS#INFORMATICS#PRACTICES.
science#and#commerce#both#have#physical#education.1234
I#like#computer#science.
Believe#in#Yourself.
8
PRACTICAL – 7
Open a text file [Link] in append mode to add new lines and read that
text file in different ways.
f=open("D:\\[Link]","a+")
[Link]("\nHello World")
[Link]("\nYou are using Python programming language\n")
[Link](0)
s=[Link]()
print(s)
[Link]("Good bye\n")
[Link](0)
s=[Link](5)
print(s)
s=[Link](200)
print(s)
s=[Link](225)
print(s)
print()
for i in s:
print(i,end='')
print(len(i))
[Link]()

Output:

SCIENCE HAS COMPUTER SCIENCE.


Think good ,be good ,do good.
COMMERCE HAS INFORMATICS PRACTICES.
science and commerce both have physical education.1234
I like computer science.
9
Believe in Yourself.
Hello World
You are using Python programming language

SCIEN
CE HAS COMPUTER SCIENCE.

['Think good ,be good ,do good.\n', 'COMMERCE HAS INFORMATICS


PRACTICES.\n', 'science and commerce both have physical education.1234\n', 'I
like computer science.\n', 'Believe in Yourself.\n', 'Hello World\n', 'You are using
Python programming language\n', 'Good bye\n']

Think good ,be good ,do good.


30
COMMERCE HAS INFORMATICS PRACTICES.
36
science and commerce both have physical education.1234
55
I like computer science.
25
Believe in Yourself.
21
Hello World
12
You are using Python programming language
42
Good bye
9

10
PRACTICAL – 8
Open a text file [Link] in read mode and count total characters,
alphabets, uppercase characters, lowercase characters, vowels,
consonants, digits, spaces, special characters, etc.

f=open("D:\\[Link]","r")
c,d,lc,uc,sp,oc,vowel,consonant,alpha=0,0,0,0,0,0,0,0,0
s=[Link]()
while s!='':
print(s)
for i in s:
if [Link]():
uc+=1
elif [Link]():
lc+=1
elif [Link]():
d+=1
elif [Link]():
sp+=1
else:
oc+=1
if [Link]():
alpha+=1
if i in ['a','e','i','o','u','A','E','I','O','U']:
vowel+=1
else:
consonant+=1
11
c+=1
s=[Link]()
print("Total characters=",c)
print("Total uppercase characters=",uc)
print("Total lowercase characters=",lc)
print("Total digits=",d)
print("Total spaces=",sp)
print("Total special characters=",oc)
print("Total Alphabets=",alpha)
print("Total Vowels=",vowel)
print("Total consonants=",consonant)
[Link]()

Output:

SCIENCE HAS COMPUTER SCIENCE.

Think good ,be good ,do good.

COMMERCE HAS INFORMATICS PRACTICES.

science and commerce both have physical education.1234

I like computer science.

Believe in Yourself.

12
Hello World

You are using Python programming language

Good bye

Total characters= 260


Total uppercase characters= 65
Total lowercase characters= 145
Total digits= 4
Total spaces= 38
Total special characters= 8
Total Alphabets= 210
Total Vowels= 84
Total consonants= 126

13
PRACTICAL – 9
Open a text file [Link] and change all the characters from ‘e’ to ‘z’
and ‘E’ to ‘Z’.

import os
f=open("D:\\[Link]","r")
f1=open("D:\\[Link]","w+")
s=[Link]()
while s!='':
for i in s:
if i=="e":
[Link]("z")
elif i=="E":
[Link]("Z")
else:
[Link](i)
s=[Link]()
[Link]()
[Link]()
[Link]("D:\\[Link]")
[Link]("D:\\[Link]","D:\\[Link]")
f=open("D:\\[Link]","r")
s=[Link]()
print(s)
[Link]()

14
Output:

SCIZNCZ HAS COMPUTZR SCIZNCZ.


Think good ,bz good ,do good.
COMMZRCZ HAS INFORMATICS PRACTICZS.
scizncz and commzrcz both havz physical zducation.1234
I likz computzr scizncz.
Bzlizvz in Yourszlf.
Hzllo World
You arz using Python programming languagz
Good byz

15
PRACTICAL – 10
Remove all the lines from [Link] that contain the character 'a' in a
file.
import os
f=open("D:\\[Link]","r")
f1=open("D:\\[Link]","w+")
s=[Link]()
while s!='':
if [Link]("a")= = -1 and [Link]("A")= = -1:
[Link](s)
s=[Link]()
[Link]()
[Link]()
[Link]("D:\\[Link]")
[Link]("D:\\[Link]","D:\\[Link]")
f=open("D:\\[Link]","r")
s=[Link]()
print(s)
[Link]()
Output:
Think good ,be good ,do good.
I like computer science.
Believe in Yourself.
Hello World
Good bye

16
PRACTICAL – 11
Python program to input records in binary file and display them.
import pickle
f=open("D:\\[Link]","wb")
while True:
grno=int(input("Enter grno:"))
name=input("Enter name:")
per=float(input("Enter per:"))
stud_data={'GRNO':grno,'NAME':name,'PER':per}
[Link](stud_data,f)
ans=input("Do you want to add more records?:")
if ans!='y' and ans!='Y':
break
[Link]()
f=open("D:\\[Link]","rb")
try:
while True:
stud=[Link](f)
print(stud)
except EOFError:#Exception(error) handling
pass
[Link]()

17
Output:
Enter grno:1
Enter name:DAVID
Enter per:85.4
Do you want to add more records?:Y

Enter grno:2
Enter name:MARCUS
Enter per:96.4
Do you want to add more records?:Y

Enter grno:3
Enter name:ALEX
Enter per:79.6
Do you want to add more records?:N

{'GRNO': 1, 'NAME': 'DAVID', 'PER': 85.4}


{'GRNO': 2, 'NAME': 'MARCUS', 'PER': 96.4}
{'GRNO': 3, 'NAME': 'ALEX', 'PER': 79.6}

18
PRACTICAL – 12
Python program to append records in binary file and display them.
import pickle
f=open("D:\\[Link]","ab")
while True:
grno=int(input("Enter grno:"))
name=input("Enter name:")
per=float(input("Enter per:"))
stud_data={'GRNO':grno,'NAME':name,'PER':per}
[Link](stud_data,f)
ans=input("Do you want to add more records?:")
if ans!='y' and ans!='Y':
break
[Link]()
f=open("D:\\[Link]","rb")
try:
while True:
stud=[Link](f)
print(stud)
except EOFError:#Exception(error) handling
pass
[Link]()

19
Output:
Enter grno:4
Enter name:PETER
Enter per:69.8
Do you want to add more records?:Y

Enter grno:5
Enter name:PATRICK
Enter per:71.8
Do you want to add more records?:N

{'GRNO': 1, 'NAME': 'DAVID', 'PER': 85.4}


{'GRNO': 2, 'NAME': 'MARCUS', 'PER': 96.4}
{'GRNO': 3, 'NAME': 'ALEX', 'PER': 79.6}
{'GRNO': 4, 'NAME': 'PETER', 'PER': 69.8}
{'GRNO': 5, 'NAME': 'PATRICK', 'PER': 71.8}

20
PRACTICAL – 13
Python program to search a record from binary file and display it.
import pickle
f=open("D:\\[Link]","rb")
found='n'
grno=int(input("Enter grno to be searched:"))
try:
while True:
stud=[Link](f)
if grno==stud['GRNO']:
print('NAME OF STUDENT:',stud['NAME'])
print('PERCENTAGE OF STUDENT:',stud['PER'])
found='y'
except EOFError:#Exception(error) handling
pass
if found=='n':
print("grno not present in file")
[Link]()

Output:
Enter grno to be searched:4
NAME OF STUDENT: PETER
PERCENTAGE OF STUDENT: 69.8

21
PRACTICAL – 14
Python program to modify a record from binary file.
import pickle
import os
f=open("D:\\[Link]","rb")
f1=open("D:\\[Link]","wb")
found='n'
grno=int(input("Enter grno to be modified:"))
try:
while True:
stud=[Link](f)
if grno==stud['GRNO']:
name=input("Enter name:")
per=float(input("Enter percentage:"))
stud['NAME']=name
stud['PER']=per
found='y'
[Link](stud,f1)
except EOFError:#Exception(error) handling
pass
if found=='n':
print("grno not present in file")
[Link]()
[Link]()
[Link]("D:\\[Link]")
[Link]("D:\\[Link]","D:\\[Link]")
f=open("D:\\[Link]","rb")
22
try:
while True:
stud=[Link](f)
print(stud)
except EOFError:
pass
[Link]()

Output:
Enter grno to be modified:4
Enter name:PIETER
Enter percentage:79.8

{'GRNO': 1, 'NAME': 'DAVID', 'PER': 85.4}


{'GRNO': 2, 'NAME': 'MARCUS', 'PER': 96.4}
{'GRNO': 3, 'NAME': 'ALEX', 'PER': 79.6}
{'GRNO': 4, 'NAME': 'PIETER', 'PER': 79.8}
{'GRNO': 5, 'NAME': 'PATRICK', 'PER': 71.8}

23
PRACTICAL – 15
Python program to delete a record from binary file.
import pickle
import os
f=open("D:\\[Link]","rb")
f1=open("D:\\[Link]","wb")
found='n'
grno=int(input("Enter grno to be deleted:"))
try:
while True:
stud=[Link](f)
if grno==stud['GRNO']:
found='y'
else:
[Link](stud,f1)
except EOFError:#Exception(error) handling
pass
if found=='n':
print("grno not present in file")
[Link]()
[Link]()
[Link]("D:\\[Link]")
[Link]("D:\\[Link]","D:\\[Link]")
f=open("D:\\[Link]","rb")
try:
while True:
stud=[Link](f)
24
print(stud)
except EOFError:
pass
[Link]()

Output:
Enter grno to be deleted:4

{'GRNO': 1, 'NAME': 'DAVID', 'PER': 85.4}


{'GRNO': 2, 'NAME': 'MARCUS', 'PER': 96.4}
{'GRNO': 3, 'NAME': 'ALEX', 'PER': 79.6}
{'GRNO': 5, 'NAME': 'PATRICK', 'PER': 71.8}

25
PRACTICAL – 16
Python program to insert student records in csv file.
import csv
fields=['GRNO','NAME','PER']
rows=[]
while True:
grno=int(input("Enter GRNO:"))
name=input("Enter NAME:")
per=float(input("Enter PERCENTAGE:"))
[Link]([grno,name,per])
choice=input("Do you want to insert more records[Y/N]:")
if choice!='Y' and choice!='y':
break
f=open("D:\\[Link]",'w',newline='')
csv_writer=[Link](f)
csv_writer.writerow(fields)
for i in rows:
csv_writer.writerow(i)
[Link]()
with open("D:\\[Link]",'r') as f:
csv_reader=[Link](f)
for r in csv_reader:
print(','.join(r))
print(csv_reader.line_num-1,"Rows displayed")
[Link]()

26
Output:-
Enter GRNO:1
Enter NAME:Patrick williams
Enter PERCENTAGE:79.7
Do you want to insert more records[Y/N]:y

Enter GRNO:2
Enter NAME:Gary Simmons
Enter PERCENTAGE:88.4
Do you want to insert more records[Y/N]:y

Enter GRNO:3
Enter NAME:Ben Collins
Enter PERCENTAGE:74.6
Do you want to insert more records[Y/N]:y

Enter GRNO:4
Enter NAME:Paul White
Enter PERCENTAGE:91.4
Do you want to insert more records[Y/N]:n

GRNO,NAME,PER
1,Patrick williams,79.7
2,Gary Simmons,88.4
3,Ben Collins,74.6
4,Paul White,91.4
4 Rows displayed

27
PRACTICAL – 17
Python program to search a student record from csv file.
import csv
with open("D:\\[Link]",'r') as f:
found='n'
GR=input("Enter grno to be searched:")
csv_reader=[Link](f)
for r in csv_reader:
if r[0]==GR:
print("Name=",r[1])
print("Percentage=",r[2])
found='y'
if found=='n':
print("Invalid GRNO to display")
[Link]()

Output :-
Enter grno to be searched:2
Name= Gary Simmons
Percentage= 88.4

28
PRACTICAL – 18
Python program to modify a student record in csv file.
import csv
import os
found='n'
error='n'
try:
f=open("D:\\[Link]",'r')
except FileNotFoundError:
print("File does not exist")
error='y'
if error=='n':
row=[]
f1=open("D:\\[Link]",'w',newline='')
grno=input("Enter grno:")
csv_reader=[Link](f)
csv_writer=[Link](f1)
for r in csv_reader:
if r[0]==grno:
name=input("Enter name:")
per=input("Enter per:")
[Link](grno)
[Link](name)
[Link](per)
csv_writer.writerow(row)
found='y'
else:
29
csv_writer.writerow(r)
[Link]()
[Link]()
if found=='n':
print("Grno not present to modify")
else:
print("Student record modified successfully")
[Link]("D:\\[Link]")
[Link]("D:\\[Link]","D:\\[Link]")
f=open("D:\\[Link]",'r')
csv_reader=[Link](f)
for r in csv_reader:
print(','.join(r))
print(csv_reader.line_num-1,"Rows displayed")
[Link]()

Output:-
Enter grno:2
Enter name:Garry Simmons
Enter per:88.6
Student record modified successfully
GRNO,NAME,PER
1,Patrick williams,79.7
2,Garry Simmons,88.6
3,Ben Collins,74.6
4,Paul White,91.4
4 Rows displayed

30
PRACTICAL – 19
Python program to delete a student record from csv file.
import csv
import os
found='n'
error='n'
try:
f=open("D:\\[Link]",'r')
except FileNotFoundError:
print("File does not exist")
error='y'
if error=='n':
f1=open("D:\\[Link]",'w',newline='')
grno=input("Enter grno:")
csv_reader=[Link](f)
csv_writer=[Link](f1)
for r in csv_reader:
if r[0]==grno:
found='y'
else:
csv_writer.writerow(r)
[Link]()
[Link]()
if found=='n':
print("Grno not present to delete")
else:
print("Student record deleted successfully")
31
[Link]("D:\\[Link]")
[Link]("D:\\[Link]","D:\\[Link]")
f=open("D:\\[Link]",'r')
csv_reader=[Link](f)
for r in csv_reader:
print(','.join(r))
print(csv_reader.line_num-1,"Rows displayed")
[Link]()

Output:-
Enter grno:2
Student record deleted successfully
GRNO,NAME,PER
1,Patrick williams,79.7
3,Ben Collins,74.6
4,Paul White,91.4
3 Rows displayed

32
PRACTICAL – 20
Python program to create database in MySQL using Python. Also
create table, insert records into table and display records from
MySQL table.
import [Link]
db=[Link](host="localhost",user="root",passwd="")
mycursor=[Link]()
print("-------------------------")
print("Current databses in mysql")
print("-------------------------")
[Link]("show databases;")
for x in mycursor:
print(x)
print("-------------------------")
[Link]("create database school;")
print("-------------------------")
print("Current databses in mysql")
print("-------------------------")
[Link]("show databases;")
for x in mycursor:
print(x)
print("-------------------------")
[Link]("use school;")
[Link]("create table stud(grno int primary key,\
name varchar(15),\
dob date,\
address varchar(15),\
33
per float);")
print("-------------------------")
print("Current tables in school database")
[Link]("show tables;")
print("-------------------------")
for x in mycursor:
print(x)
print("-------------------------")
print("-------------------------")
print("Structure of stud table")
print("-------------------------")
[Link]("desc stud;")
for x in mycursor:
print(x)
print("-------------------------")
while True:
grno=int(input("Enter grno:"))
name=input("Enter name:")
dob=input("Enter date of birth:")
address=input("Enter address:")
per=float(input("Enter percentage:"))
query="insert into stud values('%d','%s','%s','%s','%f');"
%(grno,name,dob,address,per)
[Link](query)
[Link]()
print([Link],"record inserted")
ch=input("Do you want to insert more records[y/n]:")

34
if ch!='y' and ch!='Y':
break
[Link]("select * from stud;")
for x in mycursor:
print(x)
print([Link],"record(s) in set")
print()
[Link]("select * from stud;")
records=[Link]()
for x in records:
print(x)
print([Link],"record(s) in set")
print()
print()
[Link]("select * from stud;")
record=[Link]()
print(record)
print()
records=[Link](2)
for x in records:
print(x)
print()
record=[Link]()
print(record)
print()

35
output:-
-------------------------
Current databses in mysql
-------------------------
('information_schema',)
('mysql',)
('performance_schema',)
('test',)
-------------------------
-------------------------
Current databses in mysql
-------------------------
('information_schema',)
('mysql',)
('performance_schema',)
('school',)
('test',)
-------------------------
-------------------------
Current tables in school database
-------------------------
('stud',)
-------------------------
-------------------------
Structure of stud table
-------------------------

36
('grno', 'int(11)', 'NO', 'PRI', None, '')
('name', 'varchar(15)', 'YES', '', None, '')
('dob', 'date', 'YES', '', None, '')
('address', 'varchar(15)', 'YES', '', None, '')
('per', 'float', 'YES', '', None, '')
-------------------------

Enter grno:1
Enter name:Paul Williams
Enter date of birth:1989-05-03
Enter address:Georgia
Enter percentage:89.5
1 record inserted

Do you want to insert more records[y/n]:y

Enter grno:2
Enter name:Bill Packwood
Enter date of birth:1990-01-12
Enter address:Miami
Enter percentage:77.6
1 record inserted

Do you want to insert more records[y/n]:y

37
Enter grno:3
Enter name:James Blackwood
Enter date of birth:1989-12-13
Enter address:Washington DC
Enter percentage:81.5
1 record inserted

Do you want to insert more records[y/n]:y

Enter grno:4
Enter name:Ray Johnson
Enter date of birth:1991-01-03
Enter address:California
Enter percentage:85.5
1 record inserted

Do you want to insert more records[y/n]:y

Enter grno:5
Enter name:Alex Perry
Enter date of birth:1988-11-28
Enter address:Redmond
Enter percentage:88.5
1 record inserted

Do you want to insert more records[y/n]:n

38
(1, 'Paul Williams', [Link](1989, 5, 3), 'Georgia', 89.5)
(2, 'Bill Packwood', [Link](1990, 1, 12), 'Miami', 77.6)
(3, 'James Blackwood', [Link](1989, 12, 13), 'Washington DC',
81.5)
(4, 'Ray Johnson', [Link](1991, 1, 3), 'California', 85.5)
(5, 'Alex Perry', [Link](1988, 11, 28), 'Redmond', 88.5)
5 record(s) in set

(1, 'Paul Williams', [Link](1989, 5, 3), 'Georgia', 89.5)


(2, 'Bill Packwood', [Link](1990, 1, 12), 'Miami', 77.6)
(3, 'James Blackwood', [Link](1989, 12, 13), 'Washington DC',
81.5)
(4, 'Ray Johnson', [Link](1991, 1, 3), 'California', 85.5)
(5, 'Alex Perry', [Link](1988, 11, 28), 'Redmond', 88.5)
5 record(s) in set

(1, 'Paul Williams', [Link](1989, 5, 3), 'Georgia', 89.5)

(2, 'Bill Packwood', [Link](1990, 1, 12), 'Miami', 77.6)


(3, 'James Blackwood', [Link](1989, 12, 13), 'Washington DC',
81.5)

(4, 'Ray Johnson', [Link](1991, 1, 3), 'California', 85.5)

39
PRACTICAL – 21
Python program to modify particular student record by increasing
percentage by 2 in MySQL table.
import [Link]
db=[Link](host="localhost",user="root",passwd="",da
tabase='school')
mycursor=[Link]()
grno=int(input("Enter grno to modify:"))
[Link]("update stud set per=per+2 where
grno='%d';"%(grno))
if [Link]==0:
print("GRNO is not found to be modified")
else:
ch=input("Are you sure to modify?")
if ch=='y' or ch=='y':
print("Record modified successfully")
else:
[Link]()
[Link]()
[Link]("select * from stud;")
for x in mycursor:
print(x)
print([Link],"record(s) in set")

40
output:-
Enter grno to modify:2

Are you sure to modify?y


Record modified successfully
(1, 'Paul Williams', [Link](1989, 5, 3), 'Georgia', 89.5)
(2, 'Bill Packwood', [Link](1990, 1, 12), 'Miami', 79.6)
(3, 'James Blackwood', [Link](1989, 12, 13), 'Washington DC',
81.5)
(4, 'Ray Johnson', [Link](1991, 1, 3), 'California', 85.5)
(5, 'Alex Perry', [Link](1988, 11, 28), 'Redmond', 88.5)
5 record(s) in set

41
PRACTICAL – 22
Python program to delete particular student record from MySQL
table.
import [Link]
db=[Link](host="localhost",user="root",passwd="",da
tabase='school')
mycursor=[Link]()
grno=int(input("Enter grno to delete:"))
[Link]("delete from stud where grno='%d';"%(grno))
if [Link]==0:
print("GRNO is not found to be deleted")
else:
ch=input("Are you sure to delete?")
if ch=='y' or ch=='y':
print("Record deleted successfully")
else:
[Link]()
[Link]()
[Link]("select * from stud;")
for x in mycursor:
print(x)
print([Link],"record(s) in set")

42
output:-
Enter grno to delete:2
Are you sure to delete?y
Record deleted successfully
(1, 'Paul Williams', [Link](1989, 5, 3), 'Georgia', 89.5)
(3, 'James Blackwood', [Link](1989, 12, 13), 'Washington DC',
81.5)
(4, 'Ray Johnson', [Link](1991, 1, 3), 'California', 85.5)
(5, 'Alex Perry', [Link](1988, 11, 28), 'Redmond', 88.5)
4 record(s) in set

43
PRACTICAL – 23
Create following table STORE in MYSQL and solve the queries
given below:

TABLE: STORE
PID PNAME DEPARTMENT QTY PRICE
1 PEN STATIONARY 1000 5
2 PENCIL STATIONARY 1000 4
3 WHEAT GROCERY 500 30
FLOUR
4 CORN GROCERY 500 45
FLOUR
5 UDAD DAL GROCERY 250 160
6 CHANA DAL GROCERY 250 180
7 DAIRY MILK BAKERY 1000 10
CHOCOLATE
8 PARLE BAKERY 1000 5
BISCUIT
9 ERASER STATIONARY 1000 3
10 WAFERS BAKERY 1000 10

Create table store (pid int primary key, pname varchar(20), department varchar(20),
qty int, price int);

Insert into store values (1,’PEN’,’STATIONARY’,1000,5);

1. To display products in ascending order of pname.


SELECT * FROM STORE ORDER BY PNAME;

2. To display products in descending order of department.


SELECT * FROM STORE ORDER BY DEPARTMENT DESC;

3. To display products of STATIONARY department.


SELECT * FROM STORE WHERE DEPARTMENT = ‘STATIONARY’;

4. To display products whose price is more than 50.


SELECT * FROM STORE WHERE PRICE>50;

5. To display PNAME and DEPARTMENT whose qty is greater than 500.


SELECT PNAME, DEPARTMENT FROM STORE WHERE QTY>500;

44
PRACTICAL – 24
Consider the table STORE and solve the queries given below:

TABLE: STORE
PID PNAME DEPARTMENT DOP QTY PRICE
1 PEN STATIONARY 2022-12-31 1000 5
2 PENCIL STATIONARY 2020-01-20 1000 4
3 WHEAT GROCERY 2022-12-01 500 30
FLOUR
4 CORN GROCERY 2021-06-06 500 45
FLOUR
5 UDAD DAL GROCERY 2021-05-13 250 160
6 CHANA DAL GROCERY 2021-03-16 250 180
7 DAIRY MILK BAKERY 2021-11-06 1000 10
CHOCOLATE
8 PARLE BAKERY 2021-10-03 1000 5
BISCUIT
9 ERASER STATIONARY 2020-05-20 1000 3
10 WAFERS BAKERY 2020-05-21 1000 10

1. To update information of WAFERS by increasing qty 500.


UPDATE STORE SET QTY=QTY+500 WHERE PNAME=’WAFFER’;

2. To display products’ information whose PNAME starts with ‘P’.


SELECT * FROM STORE WHERE PNAME LIKE ‘P%’;

3. To count total number of products department wise.


SELECT DEPARTMENT, COUNT(DEPARTMENT) FROM STORE
GROUP BY DEPARTMENT;

4. To display information about maximum price department wise.


SELECT DEPARTMENT, MAX(PRICE) FROM STORE GROUP BY
DEPARTMENT;

5. To display PNAME and their total amount as qty*price.


SELECT PNAME, QTY*PRICE “TOTAL AMOUNT” FROM STORE;

6. To display first five characters of all products’ name.


SELECT LEFT(PNAME,5) FROM STORE;

7. To display product details purchased in 2021.


SELECT * FROM STORE WHERE YEAR(DOP)=2021;

45
PRACTICAL – 25
Create following table STUDENT in MYSQL and solve the queries
given below:
TABLE: STUDENT
S_ID NAME MARKS
1 ABHAY 83
2 KUNAL 82
3 HARSHIL 95
4 SWAPNIL 77
5 AKSHAR 65

Create table student (S_ID int primary key, NAME varchar (20), MARKS int);
Insert into STUDENT values (1, ’ABHAY’, 83);

1. To display students’ data who got marks more than 80.


SELECT * FROM STUDENT WHERE MARKS>80;

2. To display maximum marks of student.


SELECT MAX (MARKS) FROM STUDENT;

3. To display minimum marks of student.


SELECT MIN (MARKS) FROM STUDENT;

4. To display sum of marks of entire class.


SELECT SUM (MARKS) FROM STUDENT;

5. To display average marks of entire class.


SELECT AVG (MARKS) FROM STUDENT;

6. To display students data in descending order of marks.


SELECT * FROM STUDENT ORDER BY MARKS DESC;

46
PRACTICAL – 26

Create following table CUSTOMER in MYSQL and solve the


queries given below:
TABLE: CUSTOMER
C_ID NAME COUNTRY
1 ALISHA INDIA
2 PRIYA INDIA
3 GEETA USA
4 SEEMA INDIA
5 AXITA AUSTRALIA

Create table CUSTOMER (C_ID int primary key, NAME varchar (20),
COUNTRY varchar (20));
Insert into CUSTOMER values (1, ‘ALISHA’, ‘INDIA’);

1. To count total customers country wise.


SELECT COUNTRY, COUNT (COUNTRY) FROM CUSTOMER GROUP
BY COUNTRY;

2. To display customers’ data whose name starts with ‘A’.


SELECT * FROM CUSTOMER WHERE NAME LIKE ‘A%’;

3. To modify customers’ country name to NEW ZEALAND whose country is


AUSTRALIA.
UPDATE CUSTOMER SET COUNTRY=’NEW ZEALAND’ WHERE
COUNTRY=’AUSTRALIA’;

4. Insert a new column PHONE which can store phone number of every
customers.
ALTER TABLE CUSTOMER ADD PHONE BIGINT;

5. Display all customers in ascending order of name.


SELECT * FROM CUSTOMER ORDER BY NAME;

47
PRACTICAL – 27
Create following tables PERSONAL and JOB in MYSQL and solve
the queries given below:
Table: Personal
Empno Name dobirth Native Hobby
123 Amit 1965-01-23 Delhi Music
127 Manoj 1976-12-12 Mumbai Writing
124 Abhai 1975-08-11 Allahabad Music
125 Vinod 1977-04-04 Delhi Sports
128 Abhay 1974-03-10 Mumbai Gardening
129 Ramesh 1981-10-28 Pune Sports

Create table Personal (Empno int primary key, Name varchar(20), dobirth date,
Native varchar(20), Hobby varchar(15));

insert into personal values(129,’Ramesh’,’1981-10-28’,’Pune’,’Sports’);

Table: Job
Sno Area App_date Salary Retd_date Dept
123 Agra 2006-01-25 5000 2026-01-25 Marketing
127 Mathura 2006-12-22 16000 2026-12-22 Finance
124 Agra 2007-08-19 10500 2027-08-19 Marketing
125 Delhi 2004-04-14 8500 2018-04-14 Sales
128 Pune 2008-03-13 7500 2028-03-13 Sales

Create table job ( Sno int references personal(empno), Area varchar(15), App_date
date, salary int, Retd_date date, Dept varchar(15));

insert into job values(123,’Agra’,’2006-01-25’,5000,


’2026-01-25’,’Marketing’);

1. Show empno, name and salary of those who have Sports as hobby.
Select [Link], [Link], [Link] from personal,
job where [Link]=job. sno and [Link]='Sports';

2. Show number of employees area wise.


select area, count(area) from job group by area;

3. Show youngest employee from each native place.


select native,max(dobirth) from personal group by native;

48
4. Show sno, name, hobby and salary in descending order of salary.
Select [Link], [Link] ,[Link], [Link] from
personal, job where [Link]=[Link] order by [Link]
desc;

5. Show the hobbies of those whose name pronounces as ‘Abhay’.


select hobby from personal where name like 'Abha%';

6. Show the appointment date and the native place of those whose name
starts with ‘A’ or ends in ‘d’.
select job.App_date, [Link] from personal, job where
[Link]=[Link] and ([Link] like 'A%' or
[Link] like '%d');

7. Show the salary expense with suitable column heading of those who
shall retire after 20-jan-2020
select salary as "salary expense" from job where retd_date >
'2020-01-20';

8. Show additional burden on the company in case salary of employees


having hobby as sports, is increased by 10%.
SELECT [Link]+[Link]*10/100 as “burden” FROM
personal,job where [Link]='Sports' and
[Link]=[Link];

9. Show the hobby of which there are 2 or more than 2 employees.


select hobby,count(hobby) from personal group by hobby having
count(hobby)>=2;

10. Show how many employees may retire today if maximum length of
service is more than 10 years.
select count(*) from job where (year(now())-year(app_date))>10;

11. Show the names and date of birth of those employees who have served
for more than 11 yrs. as on date.
Select [Link], [Link] from job,personal where
[Link]=[Link] and year(now())-year(app_date)>11;

12. Show empno, name and Increased salary of the employee by 5% of their
present salaries with hobby as Music and completed at least 3 yrs. of
service.
select [Link],[Link],[Link]+ [Link]*5/100
from personal,job where [Link]= 'Music' and
(year(now())year(job.app_date))>3 and [Link]=[Link];

49
PRACTICAL – 28
Python program to display records of those students whose
percentage is greater than 85.

import [Link]
db=[Link](host="localhost",user="root",passwd="",da
tabase='school')
mycursor=[Link]()
[Link]("select * from stud where per>85;")
for x in mycursor:
print(x)
print([Link],"record(s) in set")

output:-
(1, 'Paul Williams', [Link](1989, 5, 3), 'Georgia', 89.5)
(4, 'Ray Johnson', [Link](1991, 1, 3), 'California', 85.5)
(5, 'Alex Perry', [Link](1988, 11, 28), 'Redmond', 88.5)
3 record(s) in set

50

Common questions

Powered by AI

The 'PRACTICAL – 20' Python program uses the 'mysql.connector' package to connect to MySQL and supports operations such as creating a database, creating tables, inserting records, and querying the inserted records. It actively shows current databases and tables, describes the structure of tables, and allows insertion of new records in a controlled, iterative manner with the possibility for user input. This dynamic interaction between Python and MySQL facilitates complex data management scenarios .

In binary files, the records are serialized using the 'pickle' module, allowing more complex Python data structures. Operations require deserialization to access contents, ensuring structure during read/write. CSV files handle records in a text format easily readable by humans, supporting row-based operations with libraries like 'csv', which is more convenient for datasets with simple tabular structure .

The use of a temporary file ensures data integrity by first writing all changes to this temporary file instead of directly altering the original file. This allows the program to complete all data modifications without losing data due to unexpected errors during processing. Once modifications are complete and verified, the program replaces the original file with the modified temporary file, thus ensuring that the original data is not corrupt .

The program uses error handling by setting a 'found' variable to 'n' initially. During the file's iteration, if a record with the specified 'grno' is found, the record is modified, and the 'found' variable is changed to 'y'. At the end of the file iteration, if 'found' remains 'n', it outputs that the 'grno' is not present in the file .

The program reads the existing CSV file and writes to a temporary CSV file, excluding the record with the specified 'grno' for deletion. The program checks each record's 'grno' against the entered value, only writing records to the temporary file if they do not match. This ensures accuracy by precisely controlling which records are deleted. After successful writing, the temporary file replaces the original CSV file, ensuring data consistency .

The specific SQL operations used include sorting products by pname and department, filtering by department and price, and performing updates to increase 'qty' for specific products. Aggregation functions are also used to count products by department, find maximum prices within departments, and calculate total amounts as qty*price. These operations are intended to organize, manage, and analyze product data effectively in the database .

The program opens the binary file in append mode to add new records using the 'pickle.dump' method. It iteratively asks the user for input until they decide to stop. After closing the file, it reopens the file in read mode, and using a while loop with 'pickle.load', it iterates through the entire file, displaying each deserialized record, ensuring all records, new and old, are displayed .

The Python programs demonstrate several file operations such as reading, writing, and line-based manipulation to transform text data. For instance, replacing certain characters with others involves reading the content line by line and rewriting it to a new file after modifications. Removing lines based on specific criteria, like containing a certain character, involves filtering lines during the read-write process. These operations can significantly alter the text content and structure, preparing the data for further processing or analysis while ensuring that no unwanted data is preserved inadvertently .

Exception handling is crucial when reading records from a binary file as it ensures that the program can gracefully handle the EOFError, which occurs when the end of the file is reached unexpectedly. Without proper handling, this could terminate the program abruptly. The try-except structure allows the program to bypass this error and continue other operations or conclude safely, preserving program stability and user experience .

Data aggregation is employed using functions like COUNT, MAX, and SUM to consolidate and understand the data better. For instance, calculating the total number of products by department with COUNT, determining the maximum prices within each department using MAX, and finding total product amounts as a result of multiplying 'qty' and 'price' through SUM enables comprehensive data analysis and extracts significant business insights from raw data .

You might also like