Part A – Python Programs
Chapter 1 - Python Revision Tour
1. Write a program to find the sum and average of list in python.
Code:
#Creating list with user defined list
#Declare an empty list
l=[]
while True:
#Input through user
n=int(input("Enter no. to add into the list:"))
#Add element into the end of list
[Link](n)
#Condition to break loop by pressing X
ch=input("Press 'X' to stop:")
if ch in 'xX':
break
#Variable for sum and length
s=0
n=len(l)
for i in l:
#Computing Sum of elements
s+=i
#Computing average
avg=s/n
#Output
print("The list is:",l)
print("Sum is:",s)
print(f"Average is:{avg:.2f}")
1
Output:
2
2. Write a program to remove duplicates from the dictionary
Code:
#A program to remove dulicates from the dictionary
#Creating empty dictionary
d={}
#Ask user to enter number of key:value pairs
n=int(input("Enter no. of elements:"))
for i in range(n):
k=input("Enter Key:")
v=input("Enter value:")
d[k]=v
#Declare empty dictionary to store unique key-value pairs
uni_dict={}
#Traverse dictionary to remove duplicates and store into unique dictionary
for k in d:
val=d[k]
if val not in uni_dict.values():
uni_dict[k]=val
#Output
print("Dictionary After removing duplicates:",uni_dict)
Output:
3
Chapter 2 – Working with functions
3. Write a program to define a function to accept two integers m and
n respectively as argument and display prime numbers between
them.
Code:
#A program to display prime numbers from a range
# Function to check and display prime in the range
def prime_m_to_n(m,n):
for i in range(m, n + 1):
# all prime numbers are greater than 1
if i > 1:
for j in range(2, i):
if (i % j) == 0:
break
else:
print(i, end=' ')
# Taking input for m and n
m = int(input("Enter the value of m: "))
n = int(input("Enter the value of n: "))
# Calling the function
prime_m_to_n(m, n)
Output:
4
4. Write a program to compute interest based on different arguments
given in the function.
Code:
# Function to calculate interest
def compute_int(pri, r=5, t=1, comp=False):
"""Calculates simple or compound interest.
Parameters:
pri: Principal amount
r : Interest rate (default is 5%)
t: Time period in years (default is 1 year)
comp : If True, calculates compound interest, otherwise simple interest
(default is False)"""
if comp:
"""Compound Interest formula: A = P(1 + r/n)^(nt),
where n = 1 for annual compounding"""
amt = pri * (1 + r / 100) ** t
i = amt - pri
else:
# Simple Interest formula: SI = (P * R * T) / 100
i = (pri * r * t) / 100
return i
# Testing the function with various argument combinations
p=int(input("Enter Principle:"))
r=float(input("Enter custom rate:"))
t=float(input("Enter time:"))
# Case 1: Only principal provided, default rate and time
print("Interest (Simple, default):", compute_int(1000))
# Case 2: Principal and rate provided, default time
print("Interest (Simple, custom rate):", compute_int(p, r))
5
# Case 3: Principal, rate, and time provided
print("Interest (Simple, custom rate and time):", compute_int(p, r, t))
# Case 4: Compound interest, with custom rate and time
print(f"Interest (Compound, custom rate and time): {compute_int(p, r, t,
True):.2f}")
Output:
6
5. Write a program to largest element in a list using a function. Pass
list object as argument.
Code:
# Function to find the largest element in a list
def find_largest(l):
# Check the list is empty or not
if not l:
# Return None if the list is empty
return None
# Assume the first element is the large
large = l[0]
for i in l:
# Check if other element than first is large
if i > large:
# Update the largest if a bigger number is found
large = i
return large
# Taking input as a list
lst = eval(input("Enter list as input:"))
# Calling the function and printing the result
large_ele = find_largest(lst)
if large_ele is not None:
print(f"The largest element in the list is: {large_ele}")
else:
print("The list is empty.")
Output:
7
6. Write a program to count the number of vowels in passed string to
the function.
Code:
# A program to count the number of vowels in passed string to the function
def count_vowels(s):
# Define a set of vowels (both lowercase and uppercase)
vowels = "aeiouAEIOU"
# Initialize a counter variable
count = 0
# Loop through each character in the string
for char in s:
if char in vowels:
count += 1
return count
# Passing string and calling function
input_string = input("Enter a string: ")
print("Number of vowels:", count_vowels(input_string))
8
Chapter 3 – Exception Handling
7. Write a program to take two integers and perform addition of two
numbers handle exception when non-integers entered by user.
Code:
# A program to raise exception when a negative number is entered
# Define a function to add and return error
def add(n1,n2):
#Checking for error
if n1<0 or n2<0:
raise ValueError("Negative number entered!")
else:
#Performing Addition
return n1 + n2
#Handling exception using try
try:
no1 = int(input("Enter number1: "))
no2 = int(input("Enter number2: "))
print(f"The result is: {add(no1,no2)}")
except ValueError as e:
print(f"Error: {e}")
Output:
9
8. Write a program to find the square root of a positive number, raise
a custom exception when user enters a non-integer number
Code:
# Importing math module
import math
#Define a function
def find_square_root():
# Handling exception
try:
# Input a number
num = float(input("Enter a number: "))
# Condition to check positive integer
if num <= 0 or num % 1 != 0:
raise ValueError("Input must be a positive integer only")
# Calculating Square root
square_root = [Link](num)
# Output
print(f"The square root of {num} is {square_root}")
#Generating Error message
except ValueError as e:
print(f"Custom Error: {e}")
find_square_root()
Output:
10
Chapter 4 – File Handling
9. Write a program to replace entered word from a text file [Link].
Code:
# A program to replace entered word from a text file
# Define a function
def replace_word(f, old_word, new_word):
# Open a file to read
with open(f, 'r') as file:
# Store data read from file indt object
dt = [Link]()
# Checking the presence of old word and generating appropriate message
if old_word not in dt:
print(f"The word '{old_word}' was not found in the file.")
return
# Replace old word with new word
new_dt = [Link](old_word, new_word)
# Writing new data in the file
with open(f, 'w') as file:
[Link](new_dt)
#Output
print()
print(f"The word '{old_word}' has been replaced with '{new_word}'
successfully.")
print()
print(new_dt)
# Main Code
f = '[Link]'
old_word = input("Enter the word to be replaced: ")
new_word = input("Enter the new word: ")
replace_word(f, old_word, new_word)
11
Output:
12
10. Write a menu driven program to store and manipulate data in
binary file to insert, update, delete and display records. The data
has following structure:
Data Represents Patient Information
Dictionary {‘P_ID’:101,’P_Name’:’Shiv’,’Charges’:25000}
File Name [Link]
Menu:
1. Add Patient
2. Display Patient
3. Search Patient
4. Update Patient
5. Delete Patient
6. Exit
Code:
# import module to handle binary files data
import pickle
# A variable to mark as record found to counter loop iteration
flag = False
# Accepting data for Dictionary and dumping into binary file
def add_pat():
# Enter data as Input to add in dictionary
P_ID = int(input('Enter patient_id:'))
pname = input('Enter Patient Name:')
charges = int(input('Enter Charges:'))
# Creating the dictionary
rec = {'P_ID':P_ID,'P_Name':pname,'Charges':charges}
# Opens a file and Writing the Dictionary
f = open('[Link]','ab')
[Link](rec,f)
[Link]()
print("Record Addedd successfully.")
13
# Reading and displaying the records
def display_pat():
#Opening a binary file and reading data individually
f = open('[Link]','rb')
while True:
try:
rec = [Link](f)
print('*'*40)
print('Patient ID:',rec['P_ID'])
print('Name:',rec['P_Name'])
print('charges:',rec['Charges'])
print('*'*40)
except EOFError:
break
[Link]()
#Searching a record based on patient name
def search_pat(pname):
# Open file to search patient record
f = open('[Link]','rb')
# Iterating records using while loop
while True:
# Hnalding exception Ran out of Input and EOFError
try:
# Load records into a python object
rec = [Link](f)
# Matching and displaying records
if rec['P_Name'] == pname:
print('Patient ID:',rec['P_ID'])
print('Name:',rec['P_Name'])
print('Charges:',rec['Charges'])
14
flag = True
except EOFError:
break
if flag == False:
print('No Record found...')
[Link]()
# charges modification for a P_ID
def update_pat():
# Prompt P_ID and charges to modify record
pid = int(input('Enter a P_ID:'))
flag=False
# Open a file to verify record exists or not
f = open('[Link]','rb')
# An empty list to store the record found for the update
reclst = []
while True:
try:
rec = [Link](f)
[Link](rec)
flag=True
except EOFError:
break
[Link]()
c = int(input('Enter new Charges:'))
for i in range (len(reclst)):
if reclst[i]['P_ID']==pid:
reclst[i]['Charges'] = c
f = open('[Link]','wb')
15
for i in reclst:
[Link](i,f)
[Link]()
print("Record modified successfully...")
# Deleting a record based on P_ID
def deleteRec():
flag=False
f = open('[Link]','rb')
pid = int(input('Enter a P_ID:'))
reclst = []
while True:
try:
rec = [Link](f)
[Link](rec)
except EOFError:
break
[Link]()
f = open('[Link]','wb')
for i in reclst:
if i['P_ID']==pid:
continue
[Link](i,f)
print("Record Deleted...")
[Link]()
while True:
print('''
1. Add Patient
2. Display Patient
3. Search Patient
4. Update Patient
5. Delete Patient
16
6. Exit
''')
ch = int(input('Enter your choice:'))
if ch == 1:
add_pat()
elif ch == 2:
display_pat()
elif ch == 3:
pn = input('Enter a patient name to search:')
search_pat(pn)
elif ch == 4:
update_pat()
elif ch == 5:
deleteRec()
elif ch==6:
print("Bye Bye, Thank you for Interactions")
break
else:
print("Invalid Choice")
Output:
Main Menu
Add Patient
Display Patient
17
Search Patient
Update Patient
Delete Patient
Exit
18
11. Create a CSV file by entering user-id and password, read and
search the password for given userid.
Code:
# importing csv file
import csv
# creating a list to add record
users=[]
# define function to add user
def add_user():
# Taking input username and password
un=input("Enter Username:")
pwd=input("Enter Password:")
# Creating csv file and opening csv file in writing mode
f=open("[Link]","a",newline='')
# Creating writer object
w=[Link](f)
# Creating a row with username and password
[Link]([un,pwd])
# Closing the file
[Link]()
print("User added...")
# Defining a seach function
def search():
# Open a file to search password
f=open("[Link]","r")
# Reading data from csv file
r=[Link](f)
# Enter username to search password
un=input("Enter Username to search:")
# Traversing through records
for i in r:
# Verifying usernames and displaying password
19
if i[0]==un:
print("Your password for ", i[0], " is:",i[1])
[Link]()
# Creating main menu
while True:
print('''
1. Add user
2. Search Password
3. Exit
''')
ch=int(input("Enter Your Choice:"))
if ch==1:
add_user()
elif ch==2:
search()
elif ch==3:
break
else:
print("Invalid Choice")
Output:
Main Menu
Add User
20
Search Password
12. Write a program to create a binary file [Link] which
stores the following information in list as follows:
Structure of Data
Field Data Type
Candidate_id Integer
Candidate_Name String
Designation String
Experience Float
(i)Write a function append() to write data into binary file.
(ii) Write a function display() to display data from binary file for all
candidates whose experience is more than 10.
Code:
# Module to work with binary files
import pickle
# A function to accept data and append into binary file
def append():
with open("[Link]",'ab') as f:
C_id=int(input("Enter Candidate ID: "))
C_nm=input("Enter Candidate name: ")
C_dg=input("Enter Designation: ")
C_ex=float(input("Enter Experience: "))
rec=[C_id,C_nm,C_dg,C_ex]
[Link](rec,f)
21
# Display data after reading file contents
def display():
with open("[Link]",'rb') as f:
while True:
try:
rec=[Link](f)
if rec[-1]>10:
print(rec)
except EOFError:
break
# Calling functions
append()
display()
Output:
22
13. Write a program to generate a CSV file named [Link].
Each record of CSV contains these data:
Name of the country String
Population of country Integer
No. people participated in survey Integer
No. of people who are Happy Integer
Write user defined functions to do the following:
(i) Insert records into CSV
(ii) Display records from CSV
(iii) Update records
(iv) Delete record
Code:
# Import a module to work with csv
import csv
# a list object to store records
h=[]
# A function to create header row, run only once
def header_row():
f=open("[Link]",'w',newline='')
wo=[Link](f)
[Link](['Country','Population','Participants', 'Happy People'])
print("A CSV file with header is created...")
[Link]()
# A function to insert a record
def insert_rec():
with open('[Link]','a',newline='') as f:
country=input("Enter name of country:")
population=float(input("Enter Population (In Billion):"))
23
participants=float(input("Enter no. of participants (In Million):"))
happy=float(input("Enter no. of people who are happy (In Million):"))
h=[country, population, participants, happy]
wo=[Link](f)
[Link]([country,population,participants,happy])
print("Record inserted...")
# A function to display records
def display_rec():
with open('[Link]','r',newline='') as f:
ro=[Link](f)
for i in ro:
print(i)
# Update a record
def update_rec():
c=input("Enter country to update records:")
updated_row=[]
flg=False
with open('[Link]','r') as f:
ro=[Link](f)
for i in ro:
if i[0]==c:
flg=True
population=float(input("Enter Population (In Billion):"))
participants=float(input("Enter no. of participants (In Million):"))
happy=float(input("Enter no. of people who are happy (In Million):"))
i[1]=population
i[2]=participants
i[3]=happy
updated_row.append(i)
if flg==True:
24
with open('[Link]','w',newline='') as f:
wo=[Link](f)
[Link](updated_row)
print('Record Updated...')
else:
print('Record not found...')
# Delete Record
def delete_rec():
c=input("Enter country to update records:")
deleted_row=[]
flg=False
with open('[Link]','r') as f:
ro=[Link](f)
for i in ro:
if i[0] != c:
flg=True
deleted_row.append(i)
if flg==True:
with open('[Link]','w',newline='') as f:
wo=[Link](f)
[Link](deleted_row)
print('Record Deleted...')
else:
print('Record not found...')
# Main Menu
while True:
print('''
1. Create header row (Excute at once)
2. Insert country record
3. Display happiness record
25
4. Update Record
5. Delete Record
6. Exit
''')
ch = int(input('Enter your choice:'))
if ch==1:
header_row()
elif ch == 2:
insert_rec()
elif ch == 3:
display_rec()
elif ch == 4:
update_rec()
elif ch == 5:
delete_rec()
elif ch == 6:
print("Bye Bye, Thank you for Interactions")
break
else:
print("Invalid Choice")
Output: Main Menu
26
Create header row (Execute at Once)
Insert Country Record
Display Record
Update Record
Delete record
14. Write a menu drive program for stack operations:
Code:
def check_stack_isEmpty(stk):
if stk==[]:
return True
else:
return False
27
s=[] # An empty list to store stack elements, initially its empty
top = None # This is top pointer for push and pop operation
def main_menu():
while True:
print("Stack Implementation")
print("1 - Push")
print("2 - Pop")
print("3 - Peek")
print("4 - Display")
print("5 - Exit")
ch = int(input("Enter the your choice:"))
if ch==1:
el = int(input("Enter the value to push an element:"))
push(s,el)
elif ch==2:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("Element popped:",e)
elif ch==3:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("The element on top is:",e)
elif ch==4:
display(s)
elif ch==5:
break
else:
print("Sorry, You have entered invalid option")
28
def push(stk,e):
[Link](e)
top = len(stk)-1
def display(stk):
if check_stack_isEmpty(stk):
print("Stack is Empty")
else:
top = len(stk)-1
print(stk[top],"-Top")
for i in range(top-1,-1,-1):
print(stk[i])
def pop_stack(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
e = [Link]()
if len(stk)==0:
top = None
else:
top = len(stk)-1
return e
def peek(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]
main_menu()
29
Output:
Main Menu
Push Element
Pop Element
Peek Element
Display Stack
30
15. Write a program to Push an item into stack where a dictionary
contains the details of stationary items as follows:
stn = {“Shirt”:700,”T-Shirt”:750,”Jeans”:1150,”Trouser”:400}
(a) Write a function to push an element into stack for those
items names whose price is more than 850. Also display the
count of elements pushed into the stack.
(b) Write a function to pop an element to remove the element
and display appropriate message when the stack is empty.
Code:
stn = {}
while True:
item=input("Enter itemname:")
price=float(input("Enter Price:"))
stn[item]=price
ch=input("Press X to stop:")
if ch in 'xX':
break
def Push(stk,ele):
[Link](ele)
return stk
def Pop(stk):
if stk==[]:
return "underflow"
else:
return [Link]()
stak=[]
c=0
for i in stn:
if stn[i]>35:
Push(stak,i)
31
c+=1
print("Total Stack elements are:",c)
while True:
if stak!=[]:
print(Pop(stak))
else:
print("Stack is Empty")
break
Output:
32
Part B – MySQL Queries
Chapter 11 – Simple Queries in SQL
Set 1 – Based on Database Basic Commands
Write SQL Commands for following:
1. Create a database named practical_2025
Ans.: mysql> CREATE DATABASE practical_2025;
2. Check database is present or not in the list of databases
Ans.: Mysql> show databases;
3. Open a database
Ans.: mysql>use practical_2025
4. Create a database temp
Ans.: mysql> create database temp;
5. Delete a database temp
Ans.: drop database temp;
33
Set 2 – Based on DDL Commands
Consider the following MOVIES table and write the SQL commands based on it.
Movie_ID MovieName Type ReleaseDate ProductionCost BusinessCost
M001 Dahek Action 2022/01/26 1245000 1300000
M002 Attack Action 2022/01/28 1120000 1250000
M003 Looop Lapeta Thriller 2022/02/01 250000 300000
M004 Badhai Do Drama 2022/02/04 720000 68000
M005 Shabaash Mithu Biography 2022/02/04 1000000 800000
M006 Gehraiyaan Romance 2022/02/11 150000 120000
1. Create above table, assign Movie_ID as a primary key and insert records as
above
mysql> CREATE TABLE Movies ( Movie_ID VARCHAR(5) PRIMARY KEY,
MovieName VARCHAR(50),
Type VARCHAR(20),
ReleaseDate DATE,
ProductionCost INT,
BusinessCost INT );
INSERT INTO Movies (Movie_ID, MovieName, Type, ReleaseDate,
ProductionCost, BusinessCost) VALUES
('M001', 'Dahek', 'Action', '2022-01-26', 1245000, 1300000),
('M002', 'Attack', 'Action', '2022-01-28', 1120000, 1250000),
('M003', 'Looop Lapeta', 'Thriller', '2022-02-01', 250000, 300000),
('M004', 'Badhai Do', 'Drama', '2022-02-04', 720000, 68000),
('M005', 'Shabaash Mithu', 'Biography', '2022-02-04', 1000000, 800000),
('M006', 'Gehraiyaan', 'Romance', '2022-02-11', 150000, 120000);
34
2. Show the structure of table
mysql> desc movies;
3. Add a column named collection with decimal data type with structure 12, 2
mysql> alter table movies add column collection decimal(12,2);
35
4. Change the data type of movie_id to varchar
mysql> alter table movies modify column movie_id varchar(4);
Table Affected:
5. Rename a column MovieName to MName
mysql> alter table movies rename moviename to mname;
6. Delete a column collection
mysql> alter table movies drop column collection;
36
Set 3 – Select queries including order by
1. Display the movie name, type, releasedate and total cost of all movies
mysql > select mname, type, releasedate, productioncost + businesscost as
'total cost' from movies;
2. Display all details of action and thriller movies
mysql> select * from movies where type in ('action','thriller');
3. Display movie name, types and releasedate of all movies released in the month
of February, 2022
mysql > select mname, type, releasedate from movies where releasedate
between '2022-02-01' and '2022-02-28';
37
4. Display the details of movies whose name ends with letter k.
mysql > select * from movies where mname like '%k';
5. Display the details of movies which is not released yet
mysql > select * from movies where releasedate is null;
6. Display the movie name type release date and production cost in the
descending order of production cost
mysql> select mname, type, releasedate, productioncost from movies order by
productioncost desc;
38
Set 4 – Group by, having and aggregate functions
1. Display the number of movies for each type
mysql> select type, count(*) from movies group by type;
2. Display the number of unique movies
mysql> select count( distinct type) from movies;
3. Display the maximum production cost for each movie type
mysql> select type, max(productioncost) from movies group by type;
39
4. Display the date of movies released latest
mysql> select max(releasedate) from movies;
5. Display the average business cost of movies for each type
Mysql> select type, avg(businesscost) from movies group by type;
6. Display the type and number of movies for each type where movie type is
more than two
mysql> select type, count(*) from movies group by type having count(*)>2;
40
Set 5 – Join Queries
Create two tables as follows and write given queries below:
Table - artist
Table – Song
1. Display the cartesian product of artist and song tables:
mysql > select * from artist, song;
41
2. Display the records of artist and song using equijoin.
mysql > select * from artist, song where artist.artist_id=song.artist_id;
3. Display the records of artist and song tables using natural join.
mysql > select * from artist natural join song;
4. Display artist name, label and songs of sony music company.
mysql > select artist_name, label_owner, name from artist, song where
artist.artist_id=song.artist_id and label_owner='sony music';
5. Display artist name, song name from artist and song which song starts with ‘p’.
mysql > select artist_name, name from artist a, song s where a.artist_id =
s.artist_id and [Link] like ‘p%’;
42
Part C – Python & MySQL Connectivity Programs
Chapter 14 – Interface Python with MySQL
1. Write a program to connect with mysql database and insert a record into
database.
Code:
import [Link] as my
cn=[Link](host='localhost',user='root',passwd='root',database
='practical_2025')
cur=[Link]()
aid=int(input("Enter Artist ID:"))
aname=input("Enter Artist Name:")
lbl=input("Enter Label:")
[Link]("insert into artist
values({},'{}','{}')".format(aid,aname,lbl))
[Link]()
print("Record Inserted...")
[Link]()
Output:
43
2. Write a program to connect with mysql database and update a record into
database.
Code:
import [Link] as my
cn=[Link](host='localhost',user='root',passwd='root',database
='practical_2025')
cur=[Link]()
aid=int(input("Enter Artist ID:"))
aname=input("Enter Artist Name:")
lbl=input("Enter Label:")
[Link]("update artist set artist_name='{}',label_owner='{}'
where artist_id={}".format(aname,lbl,aid))
[Link]()
print("Record Updated...")
[Link]()
Output:
44
3. Write a program to connect with mysql database and delete a record into
database.
Code:
import [Link] as my
cn=[Link](host='localhost',user='root',passwd='root',database
='practical_2025')
cur=[Link]()
aid=int(input("Enter Artist ID to delete:"))
[Link]("delete from artist where
artist_id={}".format(aname,lbl,aid))
[Link]()
print("Record Deleted...")
[Link]()
Output:
Table:
45
4. Write a program to connect with mysql database display record of particular
label under the artist is working.
Code:
import [Link] as my
cn=[Link](host='localhost',user='root',passwd='root',database
='practical_2025')
cur=[Link]()
lbl=input("Enter Label:")
[Link]("select * from artist where label_owner='{}'".format(lbl))
dt=[Link]()
for i in dt:
print(i)
[Link]()
Output:
46