Code:: Q12.Write A Menu Driven Program To
Code:: Q12.Write A Menu Driven Program To
Code:: Q12.Write A Menu Driven Program To
Code:
def d1():
f = open('abcd.txt', 'r')
s=1
for i in f.readlines():
print('line', s, '=', end='')
if i[-1] == '\n':
print(i[-4:], end='')
else:
print(i[-3:])
s += 1
def d2():
f = open('abcd.txt', 'r')
print(f.read().upper())
def d3():
f = open('abcd.txt', 'r')
c=0
for i in f.read():
if i.isupper():
c += 1
print('no of upper case letters=', c)
def d4():
f = open('abcd.txt', 'r')
c=0
for i in f.read():
if i in 'AEIOUaeiou':
c += 1
print('no of vowels=', c)
while True:
choice = input('enter your choice:\n1 display last 3 characters of each line\n2
display contents in uppercase\n3 count no of uppercase\n4 count no of vowels\
n0 Exit\n')
if choice == '0':
exit()
elif choice == '1':
d1()
elif choice == '2':
d2()
elif choice == '3':
d3()
elif choice == '4':
d4()
Output:
Q13. Write a menu driven program to
to read the content of a text file ‘abcd.txt’ file and copy the same content in another
file ‘Copy.txt’ file
to read a word from keyboard and find out the frequency of this word in a text file
‘abcd.txt’
To read a text file ‘abcd.txt’ and copy all those lines that start with ‘the’ into
another text file ‘copy.txt’
to read the text file ‘abcd.txt’ and replace the word ‘This’ with ‘That’ in this
file. to read the text file ‘abcd.txt’ and display the content after removing the
word ‘This’ from the file
Code:
def w():
f = open('abcd.txt','r')
f1 = open('Copy.txt', 'w')
f1.write(f.read())
f1.close()
print('copied')
def r():
f = open('abcd.txt','r')
word = input('enter the word: ')
a = f.read().lower().split()
print(a.count(word.lower()))
def w1():
f = open('abcd.txt','r')
f1 = open('Copy.txt', 'w')
for i in f.readlines():
if i.strip().lower().startswith('the'):
f1.write(i)
f1.close()
def replace():
f = open('abcd.txt', 'r+')
a = f.readlines()
for i in range(len(a)):
if 'this' in a[i].lower():
l1 = a[i].split()
for j in range(len(l1)):
if l1[j].lower() == 'this':
l = list(l1[j])
if l[2].isupper():
l[2] = 'A'
else:
l[2] = 'a'
if l[3].isupper():
l[3] = 'T'
else:
l[3] = 't'
l1[j] = ''.join(l)
a[i] = ' '.join(l1) + '\n'
f.seek(0)
f.writelines(a)
f.close()
print('replaced')
def d():
f = open('abcd.txt', 'r+')
a = f.readlines()
for i in range(len(a)):
if 'this' in a[i].lower():
l1 = a[i].split()
l1 = [j for j in l1 if j.lower() != 'this']
a[i] = ' '.join(l1) + '\n'
while '\n' in a:
a.remove('\n')
f.seek(0)
f.writelines(a)
f.close()
while True:
c = input('enter your choice:\n1 copy to file Copy.txt\n2 find frequency
of a word\n3 copy lines starting with "the"\n4 Convert "this" to "that"\n5
delete "this" from file\nenter: ')
if c == '1':
w()
elif c == '2':
r()
elif c == '3':
w1()
elif c == '4':
replace()
elif c == '5':
d()
Output:
Q14. Create the tables and Write the SQL queries and capture the screens of executed
queries for the following:
Table: STOCK
NO ITEMCODE QUANTITY DATEOFPURCHASE WARRANTY
1 C201 9 21-May-2005 2
2 P1010 3 21-May-2005 4
3 S203 1 29-Sep-2004 3
4 C201 2 13-Jun-2005 1
5 P1010 1 31-Oct-2004 2
6 U34 5 21-May-2005 1
7 P1010 2 11-Jan-2006 2
Table: ITEM
ITEMCODE ITEMNAME PRICE
C201 Computer 39000
P1010 Printer 11000
S203 Scanner 4500
WC05 Camera 1200
U34 UPS 1900
i) To select item purchased after 31-Jan-2005.
ii) To list the item name in descending order of date of purchase where
quantity is more than three
iii) To count number of Items (total quantity) whose cost is more than 10000.
iv) To insert a new record in the table STOCK with following data:
8 C201 5 13-Jun-2005 1
v) To find minimum distinct item type (itemcode) from STOCK.
vi) To generate a report on each item code with the item name and total value
(quantity * Price).
vii) To find average cost of all items with more than 2 items.
viii) To find average cost of items with date of purchase is before 1-Jan-2005.
ix) To reduce the cost of all UPS by 100.
x) To delete the table STOCK.
OUTPUT-
Q 15. Create the table and write the SQL queries and capture the screens of executed
queries for the following:
1. To show all information about the Sofa’s from the interiors table.
2. To list the item name which are priced more than 10000 from the interiors table. I
3. To display item name and date of stock of those items, in which the discount
percentage is more than 15.
4. To list item name and type of items, in which data of stock is before 22- Jan-2002 in
descending order of item name.
5. To count the number of items of each type.
6. To insert new row in interiors table with following data:
11 White wood Double bed 23-Feb-2006 20000 20
7. To count distinct types from interiors table.
8. To find average discount from interiors for each type of interiors.
9. To calculate sum of price from interiors where data of stock is before 12- Feb-2002
10. To increase price of all Office table by 3000 from interiors table.
Q 16. Consider the following tables product and client.
Code:
import mysql.connector as mycon
if ('store',) not in l:
cur.execute('create database STORE')
cur.execute('use STORE')
cur.execute('create table PRODUCT (P_id varchar(10) primary
key,Productname varchar(30),Manufacturer varchar(30),price int(10))')
cur.execute('create table Client (C_id int(10) primary key,Clientname
varchar(30),City varchar(30),P_id varchar(10))')
con.commit()
else:
cur.execute('use STORE')
def inser
t():
n = 'NONE'
while n.upper() not in ('PRODUCT', 'CLIENT'):
n = input('Enter table: PRODUCT/CLIENT')
while True:
if n.upper() == 'PRODUCT':
i = input('enter P_id:')
nm = input('enter PRODUCT name:')
m = input('enter MANUFACTURER:')
p = int(input('enter PRICE:'))
cur.execute('insert into PRODUCT values("{}","{}","{}",{})'.format(i,
nm, m, p))
else:
i = int(input('enter C_id:'))
nm = input('enter CLIENT name:')
c = input('enter CITY:')
p = input('enter P_Id:')
cur.execute('insert into CLIENT values({},"{}","{}","{}")'.format(i,
nm, c, p))
o = input('Do you want to input more values:\n PRESS y for YES')
if o.lower() == 'y':
continue
else:
break
def desc():
cur.execute('select Clientname,Productname from CLIENT C,PRODUCT P
where P.P_Id=C.P_Id order by Clientname desc')
d = cur.fetchall()
print('Client_Name \t- Product_NAME')
for i in d:
print(i[0], '\t-', i[1])
def upd():
cur.execute('Update Product set Price=Price+0.05*Price')
cur.execute('Select * from Product')
d = cur.fetchall()
print('PID\tPNAME\t\tMANUFACTURER\tPRICE')
for i in d:
print(i[0],'\t',i[1],'\t',i[2],'\t\t',i[3])
def delete():
cur.execute('delete from Client where city="Bangalore"')
def count():
cur.execute('select count(*),city from Client group by City')
d = cur.fetchall()
print('COUNT(*)\tCITY')
for i in d:
print(i[0], '\t\t', i[1])
def alter():
cur.execute('Alter table Client Modify City Varchar(50)')
print(‘updated’)
cur.execute('use STORE')
while True:
a = input('choose your option:\n1 to INSERT\n2 to DISPLAY
CLIENTNAME AND PRODUCT PURCHASED\n3 to increase each product
price by 5%\n4 to DELETE records of people from Bangalore\n5 to DISPLAY
NUMBER OF CLIENTS FROM EACH CITY\n6 to increase the width of
column city to 50\n0 to EXIT\n')
print()
if a == '0':
exit()
elif a == '1':
insert()
elif a == '2':
desc()
elif a == '3':
upd()
elif a == '4':
delete()
elif a == '5':
count()
elif a == '6':
alter()
print()
con.commit()
Output:
Q17. Following is the structure of each record in a data file named
“PRODUCT.DAT”.
{"prod_code":value, "prod_desc":value, "stock":value}
The values for prod_code and prod_desc are strings, and the value for stock is an integer.
Write a menu driven program using functions
to enter records
to display all records
to update the file with a new value of stock. The stock and the product_code, whose stock is
to be updated, are to be input during the execution of the function.
Code:
import pickle
def main_menu():
while True:
choice = input('Enter your choice:\n0 to exit\n1 to add records\n2 to
display records\n3 to update stock\n')
if choice == '0':
exit()
elif choice == '1':
add_record()
elif choice == '2':
display_records()
elif choice == '3':
update_stock()
else:
print('Invalid input')
print()
def add_record():
file = open('PRODUCT.DAT', 'ab')
while True:
record = {}
record['code'] = input('Enter product code: ')
record['description'] = input('Enter product description: ')
record['stock'] = int(input('Enter stock quantity: '))
pickle.dump(record, file)
continue_input = input('Do you want to add more records? (yes/no): ')
if continue_input.lower() != 'yes':
break
file.close()
def display_records():
file = open('PRODUCT.DAT', 'rb')
file.seek(0)
while True:
try:
record = pickle.load(file)
print(record['code'], '\t', record['description'], '\t', record['stock'])
except EOFError:
file.close()
break
def update_stock():
file = open('PRODUCT.DAT', 'rb')
file.seek(0)
code = input('Enter product code to update stock: ')
updated_records = []
while True:
try:
record = pickle.load(file)
if record['code'] == code:
new_stock = int(input('Enter new stock quantity: '))
record['stock'] = new_stock
updated_records.append(record)
except EOFError:
file.close()
break
file = open('PRODUCT.DAT', 'wb')
for r in updated_records:
pickle.dump(r, file)
file.close()
main_menu()
Output:
Q 18. Given a binary file “STUQ2.DAT”, containing records of the following type:
[S_Admno, S_Name, Percentage]
Where these three values are:
S_Admno – Admission Number of student (string) S_Name –
Name of student (string)
Percentage – Marks percentage of student (float)
Write a menu driven program using functions
to enter records
to display all records
to read contents of the file “STUDENT.DAT” and display the details of those students
whose percentage is above 75
Code:
import pickle
def add_student_record():
file = open('STUDENT.DAT', 'ab')
while True:
admission_number = input('Enter admission number: ')
student_name = input('Enter name: ')
percentage = float(input('Enter percentage: '))
pickle.dump([admission_number, student_name, percentage], file)
continue_input = input('Do you want to enter more records? (yes/no): ')
if continue_input.lower() != 'yes':
break
file.close()
def display_student_records():
file = open('STUDENT.DAT', 'rb')
file.seek(0)
while True:
try:
record = pickle.load(file)
print(record[0], '\t', record[1], '\t', record[2])
except EOFError:
file.close()
break
def display_students_above_75_percent():
file = open('STUDENT.DAT', 'rb')
file.seek(0)
students_above_75_percent = []
while True:
try:
record = pickle.load(file)
while True:
choice = input('Enter your choice:\n0 to exit\n1 to enter records\n2 to
display records\n3 to display records with percentage > 75%\n')
print()
if choice == '0':
exit()
elif choice == '1':
add_student_record()
elif choice == '2':
display_student_records()
elif choice == '3':
display_students_above_75_percent()
Output:
Q 19. Assuming the tuple Vehicle as follows:
(vehicletype, no_of_wheels)
where vehicletype is a string and no_of_wheels is an integer. Write a menu driven
program using functions
to enter records
to display all records
to count and display the number of records present in the file.
Code:
import pickle
def add_vehicle_record():
file = open('vehicle.DAT', 'ab')
while True:
vehicle_type = input('Enter vehicle type: ')
num_of_wheels = int(input('Enter number of wheels: '))
pickle.dump((vehicle_type, num_of_wheels), file)
continue_input = input('Do you want to enter more records? (yes/no): ')
if continue_input.lower() != 'yes':
break
file.close()
def display_vehicle_records():
file = open('vehicle.DAT', 'rb')
file.seek(0)
while True:
try:
record = pickle.load(file)
print(record[0], '\t\t', record[1])
except EOFError:
file.close()
break
file.close()
def count_vehicle_records():
file = open('vehicle.DAT', 'rb')
file.seek(0)
count = 0
while True:
try:
pickle.load(file)
count += 1
except EOFError:
file.close()
break
print('Number of Records:', count)
file.close()
while True:
choice = input('Enter your choice:\n0 to exit\n1 to enter records\n2 to
display records\n3 to count the number of records\n')
print()
if choice == '0':
exit()
elif choice == '1':
add_vehicle_record()
elif choice == '2':
display_vehicle_records()
elif choice == '3':
count_vehicle_records()
else:
pass
Output:
Q 20. Create a file PRODUCT.CSV. Sample data of the file is as follows:
Code:
import csv
def insert_initial_records():
with open('PRODUCT.csv', 'w', newline='') as file:
header = ['PID', 'PNAME', 'COST', 'QUANTITY']
records = [
['P1', 'BRUSH', 50, 200],
['P2', 'TOOTHPASTE', 120, 150],
['P3', 'COMB', 40, 300],
['P4', 'SHEETS', 100, 500],
['P5', 'PEN', 10, 250]
]
writer = csv.writer(file, delimiter=',')
writer.writerow(header)
writer.writerows(records)
print("records inserted")
def display_records():
with open('PRODUCT.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row[0], '\t', row[1], '\t', row[2], '\t', row[3])
def insert_records_into_pro1():
with open('PRODUCT.csv', 'r') as file:
with open('PRO1.csv', 'w', newline='') as file_pro1:
reader = csv.reader(file)
writer = csv.writer(file_pro1, delimiter=',')
for row in reader:
try:
if int(row[3]) > 150:
writer.writerow(row)
except ValueError:
writer.writerow(row)
print("records inserted")
def calculate_cost_sum():
with open('PRODUCT.csv', 'r') as file:
reader = csv.reader(file)
total_cost = 0
for row in reader:
try:
total_cost += int(row[2])
except ValueError:
pass
print('Sum of the cost of all products:', total_cost)
def find_record_with_max_cost():
with open('PRODUCT.csv', 'r') as file:
reader = csv.reader(file)
header = next(reader)
max_cost = 0
max_cost_record = None
for row in reader:
try:
cost = int(row[2])
if cost > max_cost:
max_cost = cost
max_cost_record = row
except ValueError:
pass
if max_cost_record:
print('Record with max cost:')
print(header[0], '\t', header[1], '\t', header[2], '\t', header[3])
print(max_cost_record[0], '\t', max_cost_record[1], '\t',
max_cost_record[2], '\t', max_cost_record[3])
else:
print('No record found with max cost.')
while True:
choice = input('Enter your choice:\n0 to exit\n1 to enter initial records\n2 to
display records\n3 to insert records with quantity > 150 into PRO1.csv\n4 to
calculate the sum of the cost of all products\n5 to find and display the record
with
Output:
Q 21. Create a file Tour.csv having headings as follows TID,DESTINATION,DAYS,FARE. Sample
data of file is as follows:
Code:
import csv
def insert_initial_records():
with open('Tour.csv', 'w', newline='') as file:
header = ['TID', 'DESTINATION', 'DAYS', 'FARE']
records = [
['T10', 'AUSTRALIA', 10, 300],
['T11', 'AUSTRIA', 15, 750],
['T12', 'RAJASTHAN', 10, 700],
['T13', 'FRANCE', 12, 650]
]
writer = csv.writer(file, delimiter=',')
writer.writerow(header)
writer.writerows(records)
def display_records():
with open('Tour.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row[0], '\t', row[1], '\t', row[2], '\t', row[3])
def display_records_within_fare_range():
with open('Tour.csv', 'r') as file:
reader = csv.reader(file)
records_within_range = []
for row in reader:
try:
fare = int(row[3])
if 500 < fare < 750:
records_within_range.append(row)
except ValueError:
pass
if not records_within_range:
print('No records with fare between 500 and 750.')
else:
print('TID\tDESTINATION\tDAYS\tFARE')
for row in records_within_range:
print(row[0], '\t', row[1], '\t', row[2], '\t', row[3])
while True:
choice = input('Enter your choice:\n0 to exit\n1 to enter initial records\n2 to
display records\n3 to display records with fare between 500 and 750\n')
print()
if choice == '0':
exit()
elif choice == '1':
insert_initial_records()
elif choice == '2':
display_records()
elif choice == '3':
display_records_within_fare_range()
Output:
Code:
def MakePush(Package):
n = input('enter Package info:')
Package += [n]
def MakePop(Package):
if Package == []:
print('Empty stack, no value to delete')
else:
print('Deleted item:', Package.pop())
Package = []
while True:
c = input('press:\n0.EXIT \n1.ADD \n2.REMOVE\n')
if c == '0':
exit()
elif c == '1':
MakePush(Package)
elif c == '2':
MakePop(Package)
Output:
Q 23. Write the functions in Python push (stk, item ) and pop(stk) to check whether the
stack is empty, to add a new item, to delete an item and display the stack respectively.
Implement the menu driven program
Code:
def push(stk, item):
stk += [item]
def pop(stk):
if stk == []:
print('Stack is empty, nothing to delete')
else:
print('Deleted element:', stk.pop())
def emptystack(stk):
if stk == []:
print('Oops! The stack is empty')
else:
print('Stack is not empty')
def display(stk):
for i in stk[::-1]:
print(i)
stk = []
while True:
choice = input('0.EXIT\n1.ADD item to stack\n2.DELETE item from stack\
n3.FIND whether stack is empty or not\n4.DISPLAY STACK\n')
if choice == '0':
exit()
elif choice == '1':
item = input('Enter element to insert:')
push(stk, item)
elif choice == '2':
pop(stk)
elif choice == '3':
emptystack(stk)
elif choice == '4':
display(stk)
Output:
Q24. Write a program to perform push operation on a stack to push all prime numbers from
a list entered by a user.
Code:
while True:
choice = input('Enter a number you want to insert or press s to stop entering:
')
try:
num = int(choice)
l.append(num)
except ValueError:
if choice.lower() == 's':
break
else:
print('Invalid input')
for i in l[::-1]:
j=2
r=0
if i == 1 or i == 0:
r=1
else:
while j <= math.sqrt(i):
if i % j == 0:
r=1
break
j += 1
if r == 0:
stk.append(i)
print(stk)
Output: