Report File Programs (24-25) (Solved) - Sample #1
Report File Programs (24-25) (Solved) - Sample #1
Write a menu driven program to perform mathematical calculations like Addition, Subtraction,
Division, Multiplication between two integers. The program should continue running until user gives the
choice to quit.
return a + b
return a - b
return a * b
if b != 0:
return a / b
else:
while True:
print("""
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Quit
""")
print("Exiting program.")
break
if choice == 1:
elif choice == 2:
elif choice == 3:
elif choice == 4:
else:
S=1+x1/2!+x2/3!+…..+xn/(n+1)!
total = 1
fact = 1
fact *= (i + 1)
total += (x ** i) / fact
***
*****
*******
n = 4 # Number of rows
4. Write a program which takes the number of people of various age groups as input and prints a ticket.
At the end of the journey, the program states the number of passengers of different age groups who
travelled and the total amount received as collection of fares.
c_fare = 5
a_fare = 10
s_fare = 7
c_count = 0
a_count = 0
s_count = 0
total = 0
while True:
print("""
1. Enter Passenger
""")
if ch == 1:
c_count += 1
total += c_fare
a_count += 1
total += a_fare
else:
s_count += 1
total += s_fare
elif ch == 2:
break
5. Write a program that defines a function ModifyList(L) which receives a list of integers , updates all
those elements which have 5 as the last digit with 1 and rest by 0.
def ModifyList(L):
for i in range(len(L)):
if L[i] % 10 == 5:
L[i] = 1
else:
L[i] = 0
ModifyList(my_list)
OUTPUT
6. Write a program that defines a function MinMax(T) which receives a tuple of integers and returns the
maximum and minimum value stored in tuple.
def MinMax(T):
OUTPUT
Maximum value: 9
Minimum value: 1
7.Write a program with function INDEX_LIST(L), where L is the list of elements passed as argument to
the function. The function returns another list named ‘indexlist’ that stores the indices of all Non-Zero
elements of L. For e.g. if L contains [12,4,0,11,0,56] then after execution indexlist will have[0,1,3,5]
def INDEX_LIST(L):
indexlist = []
for i in range(len(L)):
if L[i] != 0:
indexlist.append(i)
return indexlist
indexlist = INDEX_LIST(user_input)
OUTPUT
stock = []
OUTPUT
Enter quantity: 10
9. Write a menu driven program with user defined functions to create a text file MyFile.txt, where
choices are:
1-Create text file 2- Generate a frequency list of all the words resent in it
import os
def create_file():
f.write(content)
def generate_frequency():
if not os.path.exists("MyFile.txt"):
return
text = f.read()
words = text.split()
frequency = {}
if word in frequency:
frequency[word] += 1
else:
frequency[word] = 1
def max_words_line():
if not os.path.exists("MyFile.txt"):
return
max_line = ""
max_count = 0
count = len(line.split())
max_count = count
max_line = line.strip()
while True:
print("""
4. Quit
""")
if choice == 1:
create_file()
elif choice == 2:
generate_frequency()
elif choice == 3:
max_words_line()
elif choice == 4:
break
else:
OUTPUT
Frequency list: {'This': 1, 'is': 3, 'the': 3, 'first': 1, 'line.': 1, 'Here': 1, 'second': 1, 'line': 1, 'which': 1, 'a': 1,
'bit': 1, 'longer.': 1, 'And': 1, 'last': 1}
Line with maximum words: Here is the second line which is a bit longer.
10. Write a program to remove all the lines that contains character ‘a’ in a file and write them to
another file.
import os
temp_file = "temp.txt"
lines = infile.readlines()
if 'a' in line:
pass
input_file = "MyFile.txt"
output_file = "FilteredFile.txt"
remove_lines_with_a(input_file, output_file)
OUTPUT
No 'a' here.
No 'a' here.
11.Write a program to create a menu driven program using user defined functions to manage details of
Applicants in a binary file .DAT . Applicant details include(AppID,AName,Qualification)
import pickle
import os
def add_applicant():
pickle.dump(applicant, file)
def view_applicants():
if not os.path.exists("Applicants.DAT"):
return
try:
while True:
applicant = pickle.load(file)
except EOFError:
def search_applicant():
if not os.path.exists("Applicants.DAT"):
return
search_id = int(input("Enter Applicant ID to search: "))
found = False
try:
while True:
applicant = pickle.load(file)
if applicant['AppID'] == search_id:
found = True
break
except EOFError:
if not found:
def delete_applicant():
if not os.path.exists("Applicants.DAT"):
return
found = False
applicants = []
try:
while True:
applicant = pickle.load(file)
if applicant['AppID'] != delete_id:
applicants.append(applicant)
else:
found = True
except EOFError:
pass
if found:
pickle.dump(applicant, file)
else:
while True:
print("""
1. Add Applicant
3. Search Applicant by ID
4. Delete Applicant by ID
5. Quit
""")
if choice == 1:
add_applicant()
elif choice == 2:
view_applicants()
elif choice == 3:
search_applicant()
elif choice == 4:
delete_applicant()
elif choice == 5:
break
else:
OUTPUT
1. Add Applicant
3. Search Applicant by ID
4. Delete Applicant by ID
5. Quit
1. Add Applicant
3. Search Applicant by ID
4. Delete Applicant by ID
5. Quit
1. Add Applicant
3. Search Applicant by ID
4. Delete Applicant by ID
5. Quit
12. Write a menu driven program to implement stack data structure using list to Push and Pop Book
details(BookID,BTitle,Author,Publisher,Price). The available choices are:
5-QUIT
stack = []
def push():
book = {
'BookID': book_id,
'BTitle': title,
'Author': author,
'Publisher': publisher,
'Price': price
stack.append(book)
def pop():
if len(stack) == 0:
else:
book = stack.pop()
def peek():
if len(stack) == 0:
print("Stack is empty.")
else:
def traverse():
if len(stack) == 0:
print("Stack is empty.")
else:
print("Books in Stack:")
print(book)
while True:
print("""
1. PUSH
2. POP
3. PEEK
4. TRAVERSE
5. QUIT
""")
if choice == 1:
push()
elif choice == 2:
pop()
elif choice == 3:
peek()
elif choice == 4:
traverse()
elif choice == 5:
print("Exiting...")
break
else:
OUTPUT
1. PUSH
2. POP
3. PEEK
4. TRAVERSE
5. QUIT
1. PUSH
2. POP
3. PEEK
4. TRAVERSE
5. QUIT
Books in Stack:
{'BookID': 'B001', 'BTitle': 'Python Programming', 'Author': 'John Smith', 'Publisher': 'TechBooks', 'Price':
'25.99'}
1. PUSH
2. POP
3. PEEK
4. TRAVERSE
5. QUIT
Enter your choice: 2
Popped Book: {'BookID': 'B001', 'BTitle': 'Python Programming', 'Author': 'John Smith', 'Publisher':
'TechBooks', 'Price': '25.99'}
1. PUSH
2. POP
3. PEEK
4. TRAVERSE
5. QUIT
Exiting...
13 .Write definition of a user defined function PUSHNV(N) which receives a list of strings in the
parameter N and pushes all strings which have no vowels present in it , into a list named NoVowel.
The program then use the function PUSHNV() to create a stack of words in the list NoVowel so that it
stores only those words which do not have any vowel present in it, from the list ALL. Thereafter pop
each word from the list NoVowel and display all popped words. When the stack is empty display the
message “Empty Stack”.
def pushnv(n):
novowel = []
vowels = 'aeiouAEIOU'
for word in n:
novowel.append(word)
return novowel
all_words = eval(input("Enter 10 words in a list like ['word1', 'word2', ...]: "))
novowel = pushnv(all_words)
while novowel:
if not novowel:
print("Empty Stack")
OUTPUT
Enter 10 words in a list like ['word1', 'word2', ...]: ['sky', 'rhythm', 'ball', 'fly', 'cat', 'xyz', 'try', 'jump', 'cry',
'bat']
Empty Stack
14. Write a program in Python using a user defined function Push(SItem) where SItem is a dictionary
containing the details of stationary items {Sname:Price}.
The function should push the names of those items in the stack who have price greater than 75, also
display the count of elements pushed onto the stack.
def push(sitem):
stack = []
count = 0
stack.append(name)
count += 1
sitem = eval(input("Enter stationary items as a dictionary like {'item1': price1, 'item2': price2, ...}: "))
OUTPUT
Enter stationary items as a dictionary like {'item1': price1, 'item2': price2, ...}: {'pen': 50, 'notebook': 100,
'pencil': 20, 'marker': 80}
15. Create a table named as CLUB in database GAMES with appropriate data type using SQL command of
following structure and constraints: CoachID Primary Key, CoachName Not Null, Age Not Null,
Sports,DateOfApp,Pay,Sex.
Sports VARCHAR(30),
DateOfApp DATE,
Sex CHAR(1)
);
16Write Python interface program using MySQL to insert rows in table CLUB in database GAMES
1, 'Kukreja',35,'Karate','1996/03/27',10000,'M';
2, 'Ravina',34,'Karate','1998-01-20',12000,'F';
3, 'Karan',32,'Squash','2000-02-19',20000,'M';
4,'Tarun',33,'Basket Ball','2005-01-01',15000,'M';
5 ,'Zubin',36,'Swimming','1998-02-24',7500,'M')
6 'Ketaki',33,'Swimming','2001-12-23',8000,'F'
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="GAMES"
cursor = conn.cursor()
query = "INSERT INTO CLUB (CoachID, CoachName, Age, Sports, DateOfApp, Pay, Sex) VALUES (%s, %s,
%s, %s, %s, %s, %s)"
data = [
cursor.executemany(query, data)
conn.commit()
cursor.close()
conn.close()
17Write Python interface program using MySQL to retrieve details of coaches as per the sport name
input by user from table CLUB in database GAMES.
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="GAMES"
cursor = conn.cursor()
cursor.execute(query, (sport,))
results = cursor.fetchall()
if results:
print("CoachID:", row[0], "Name:", row[1], "Age:", row[2], "Sport:", row[3], "DateOfApp:", row[4],
"Pay:", row[5], "Sex:", row[6])
else:
cursor.close()
conn.close()
19.Write Python interface program using MySQL to increase price by 10% in table CUSTOMER of MYORG
database
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="MYORG"
cursor = conn.cursor()
cursor.execute(query)
conn.commit()
cursor.close()
conn.close()
20.Write a Python interface program using MySQL to delete all those customers whose name contains
Kumar from table CUSTOMER in database MYORG.
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="MYORG"
cursor = conn.cursor()
cursor.execute(query)
conn.commit()
cursor.close()
conn.close()
21.. Create following tables in database MYORG with appropriate data type using SQL commands of
following structure.
);
CID INT,
);
22. Write SQL commands to insert following data in above created tables Company and Customer , also
list all data .
Table: Company
Sony Delhi TV
111
Table:Customer
Q23 Write SQL commands for the following queries based on tables Company and Customer.
To increase price by 1000 for those customers whose name starts with ‘S’.
To display customer details along with product name and company name of the product.
iv) To display customer details along with product name and company name of
the product.
SELECT CU.*, C.ProductName, C.Name AS CompanyName
FROM Customer CU
JOIN Company C ON CU.CID = C.CID;
24. Write Python interface program using MySQL to insert rows in table CLUB
in database GAMES
cursor = db.cursor()
def insert_club():
# Taking input from user for inserting data
coach_id = int(input("Enter Coach ID: "))
name = input("Enter Coach Name: ")
age = int(input("Enter Age: "))
sport = input("Enter Sport: ")
date_of_app = input("Enter Date of Appointment (YYYY-MM-DD): ")
pay = int(input("Enter Pay: "))
sex = input("Enter Sex (M/F): ")
try:
cursor.execute(query, values)
db.commit()
print("Record inserted successfully!")
except Exception as e:
db.rollback() # Rollback in case of error
print(f"Error: {e}")