Practical Programs Solution
Practical Programs Solution
Menu-driven program to create user defined functions to perform the following Text file
(Story.txt) operations: a) To write data to a text file (Any Sample text data) b) To read the entire
contents of the file and display it c) To print the statistics of the file. Read the text file and display the
total no. of characters, Total no of words and total no of digits.
def write_to_file():
file.write(data)
file.close()
def read_file():
try:
content = file.read()
file.close()
except FileNotFoundError:
def file_statistics():
try:
content = file.read()
chars = len(content)
words = len(content.split())
print("\nStatistics of Story.txt:")
file.close()
except FileNotFoundError:
def main():
while True:
print("4. Exit")
if choice == '1':
write_to_file()
read_file()
file_statistics()
break
else:
print("Invalid choice.")
main()
10) Menu-driven program to create user defined functions to perform the following Text file
(Story.txt) operations: a) Read the contents of the text file line by line and display it.(File should be
created before) b) Display all the lines starting with a letter‘s’. c) Display each word separated by a #
symbol.
def read_lines():
try:
print(line.strip())
file.close()
except FileNotFoundError:
def lines_starting_with_s():
try:
if line.startswith('s') or line.startswith('S'):
print(line.strip())
file.close()
except FileNotFoundError:
def words_separated_by_hash():
try:
words = line.split()
print("#".join(words))
file.close()
except FileNotFoundError:
while True:
print("4. Exit")
if choice == '1':
read_lines()
lines_starting_with_s()
words_separated_by_hash()
break
else:
print("Invalid choice.")
main()
11) Menu-driven program to perform the following operations on a binary file ‘Player.dat’, which has
the following structure: Player_id, Player_name, Player_game]. a) Create a function File_Create () to
add records into the file. b) Create a function File_Read () to read the records c) Create a function
Search_Data () to search for a particular Player using his Player_id. If found, print the Player details.
Otherwise print appropriate message.
import pickle
def File_Create():
# Function to read and display all records from the binary file
def File_Read():
try:
print("\nPlayer records:")
while True:
try:
print(player)
break
except FileNotFoundError:
def Search_Data():
found = False
try:
while True:
try:
player = pickle.load(file)
if player[0] == search_id:
print("\nPlayer found:", player)
found = True
break
except EOFError:
break
if not found:
except FileNotFoundError:
# Menu-driven program
def main():
while True:
print("4. Exit")
if choice == '1':
File_Create()
File_Read()
Search_Data()
break
else:
print("Invalid choice.")
main()
12) Menu-driven program to perform the following operations on a binary file ‘Employee.dat’, which
has the structure as [empid, empname, salary, design]. a) Create a function File_Create () to add
records into the file. b) Create a function File_Read () to read the records (employee data) from file.
c) Create a function Update_Data () to update the salary of employees whose designation is
‘Manager’ by Rs.5000/- and display the updated data
import pickle
def File_Create():
# Function to read and display all employee records from the binary file
def File_Read():
try:
print("\nEmployee records:")
while True:
try:
print(employee)
break
except FileNotFoundError:
def Update_Data():
try:
updated_employees = []
found = False
while True:
try:
employee = pickle.load(file)
found = True
updated_employees.append(employee)
except EOFError:
break
if found:
else:
except FileNotFoundError:
# Menu-driven program
def main():
while True:
print("4. Exit")
if choice == '1':
File_Create()
File_Read()
Update_Data()
break
else:
print("Invalid choice.")
main()
13) Menu-driven program to perform the following operations on a CSV file ‘Login.csv’, which has
the structure as [uid, passwd]: a) Create a function Create_csv () to add records to the file. b) Create
a function Read_csv() to read and display all the records from the file. c) Create a function
Search_csv() to search whether a user exists or not with the uid which is passed as an argument.
import csv
def Create_csv():
writer = csv.writer(file)
writer.writerow([uid, passwd])
def Read_csv():
try:
reader = csv.reader(file)
print("\nLogin records:")
print(row)
except FileNotFoundError:
def Search_csv(uid):
found = False
try:
reader = csv.reader(file)
found = True
break
if not found:
except FileNotFoundError:
# Menu-driven program
def main():
while True:
print("\n1. Add Login Record")
print("4. Exit")
if choice == '1':
Create_csv()
Read_csv()
Search_csv(uid)
break
else:
print("Invalid choice.")
main()
14) Menu-driven program to perform the following operations on a CSV file ‘Address.csv’, which has
the structure [Name, Mob_no, email] a) Create a function Create_csv () to add records to the file. b)
Create a function Read_csv() to read and display all the records from the file. c) Create a function
Search_csv() to search for a mobile number, if found then write only those records to a new csv file
‘NewAddress.csv’. If not found, print appropriate message.
import csv
def Create_csv():
# Function to read and display all records from the CSV file
def Read_csv():
try:
reader = csv.reader(file)
print("\nAddress records:")
print(row)
except FileNotFoundError:
# Function to search for a mobile number and write found records to 'NewAddress.csv'
def Search_csv(mob_no):
found = False
try:
reader = csv.reader(file)
with open("NewAddress.csv", "w", newline='') as new_file: # Create new CSV for found
records
writer = csv.writer(new_file)
found = True
if found:
else:
except FileNotFoundError:
# Menu-driven program
def main():
while True:
print("4. Exit")
if choice == '1':
Create_csv()
Read_csv()
Search_csv(mob_no)
break
else:
print("Invalid choice.")
main()
15) Menu-driven program to implement Stack using a list data-structure, to perform the following
operations: a) To Push an object containing Doc_ID and Doc_name of doctors who specialize in
"ENT" to the stack. b) To Pop the objects from the stack and display them. c) To display the elements
of the stack (after performing PUSH or POP)
stack = []
def push():
def pop():
if len(stack) == 0:
else:
def display_stack():
if len(stack) == 0:
print("Stack is empty.")
else:
print(doctor)
# Menu-driven program
def main():
while True:
print("4. Exit")
if choice == '1':
push()
pop()
display_stack()
break
else:
print("Invalid choice.")
main()
16) Menu driven program to integrate MySQL with Python and perform the following operations: a)
Create a database school, create a table student with fields as Rollno, Stu_Name, Stream and
Percentage. Then insert 5 records into it. b) Display all the records from the table
import mysql.connector
# Connect to MySQL
def connect_to_mysql():
return mysql.connector.connect(
def create_database_and_insert():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE school")
# Insert 5 records
def display_records():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE school")
print(row)
# Menu-driven program
def main():
while True:
print("3. Exit")
if choice == '1':
create_database_and_insert()
display_records()
break
else:
main()
17) Menu driven program to integrate MySQL with Python and perform the following operations: a)
Create a database Company, create a table Product with fields as Pid, Pname, Qty and Price. Then
insert 5 records into it. b) Display all the records from the table c) Read records from student table
and search for a particular student based on the Pid
import mysql.connector
# Function to connect to MySQL
def connect_to_mysql():
return mysql.connector.connect(
def create_database_and_insert():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
cursor.execute("""
Pname VARCHAR(100),
Qty INT,
Price FLOAT
""")
# Insert 5 records
products = [
def display_records():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
# Print records
print(row)
def search_product(pid):
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
product = cursor.fetchone()
if product:
else:
# Menu-driven program
def main():
while True:
print("4. Exit")
if choice == '1':
create_database_and_insert()
display_records()
search_product(pid)
break
else:
main()
18) Menu driven program to integrate MySQL with Python and perform the following operations: a)
Create a database Company, create a table Employee with fields as Empid, Empname, designation
and Salary. Then insert 5 records into it. b) Update the salary of an employee by 5000 whose
designation as ‘Manager’ c) Display all the records from the table. d) Delete the records from
employee based on their empid.
import mysql.connector
def connect_to_mysql():
return mysql.connector.connect(
def create_database_and_insert():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
cursor.execute("""
Empname VARCHAR(100),
designation VARCHAR(50),
Salary FLOAT
""")
# Insert 5 records
employees = [
def update_salary():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
def display_records():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
cursor.execute("SELECT * FROM Employee")
# Print records
print(row)
def delete_employee(empid):
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
# Menu-driven program
def main():
while True:
print("5. Exit")
if choice == '1':
create_database_and_insert()
elif choice == '2':
update_salary()
display_records()
delete_employee(empid)
break
else:
main()
19) Menu driven program to integrate MySQL with Python and perform the following operations: a)
Create a database Company, create a table create a table Client with fields as C_ID, ClientName, City.
b) Read records from the table and display those records whose city is ‘Delhi’. c) Delete the records
from table based on their client id d) Display all the records.
import mysql.connector
def connect_to_mysql():
return mysql.connector.connect(
def create_database_and_table():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
cursor.execute("""
ClientName VARCHAR(100),
City VARCHAR(50)
""")
# Sample data
clients = [
# Read and display records from the table where city is 'Delhi'
def display_clients_in_delhi():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
print("Clients in Delhi:")
print(row)
def delete_client(c_id):
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
def display_all_clients():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
print("All Clients:")
print(row)
conn.close() # Close connection
# Menu-driven program
def main():
while True:
print("5. Exit")
if choice == '1':
create_database_and_table()
display_clients_in_delhi()
delete_client(c_id)
display_all_clients()
break
else:
main()