REPORT FILE PROGRAM - XII
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.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
return "Error! Division by zero."
while True:
print("\nMenu:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Quit")
choice = input("Enter your choice (1-5): ")
if choice == '5':
break
if choice in ['1', '2', '3', '4']:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
if choice == '1':
print(f"Result: {add(num1, num2)}")
elif choice == '2':
print(f"Result: {subtract(num1, num2)}")
elif choice == '3':
print(f"Result: {multiply(num1, num2)}")
elif choice == '4':
print(f"Result: {divide(num1, num2)}")
else:
print("Invalid choice!")
OUTPUT:
2. Write a program to find sum of series
S=1+x1/2!+x2/3!+…..+xn/(n+1)!
import math
def sum_of_series(x, n):
series_sum = 1
for i in range(1, n + 1):
series_sum += (x ** i) / [Link](i + 1)
return series_sum
x=int(input("Enter number:"))
n=int(input("Enter length:"))
result = sum_of_series(x, n)
print(f"The sum of the series for x={x} and n={n} is: {result}")
OUTPUT:
3Write a program to print following pattern:
***
*****
*******
n=int(input("Enter number:"))
for i in range(1,n+1):
print(" "*(n-i),end="")
print("*"*(2*i-1))
OUTPUT:
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.
def calculate_fares(children, teens, adults, seniors):
fare_children = 5
fare_teens = 7
fare_adults = 10
fare_seniors = 8
total_children = children * fare_children
total_teens = teens * fare_teens
total_adults = adults * fare_adults
total_seniors = seniors * fare_seniors
total_fare = total_children + total_teens + total_adults + total_seniors
print("\n--- Ticket Summary ---")
print(f"Children (0-12 years): {children} passengers, Total: ${total_children}")
print(f"Teens (13-19 years): {teens} passengers, Total: ${total_teens}")
print(f"Adults (20-59 years): {adults} passengers, Total: ${total_adults}")
print(f"Seniors (60+ years): {seniors} passengers, Total: ${total_seniors}")
print(f"\nTotal collection: ${total_fare}")
print("----------------------")
print("Enter the number of passengers in various age groups:")
children = int(input("Children (0-12 years): "))
teens = int(input("Teens (13-19 years): "))
adults = int(input("Adults (20-59 years): "))
seniors = int(input("Seniors (60+ years): "))
calculate_fares(children, teens, adults, seniors)
OUTPUT:
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
return l
l = eval(input("Enter list:"))
modified_list = ModifyList(l)
print("Modified list:", modified_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):
min_value = min(T)
max_value = max(T)
return min_value, max_value
T = eval(input("Enter tuple:"))
min_val, max_val = MinMax(T)
print(f"Minimum value: {min_val}")
print(f"Maximum value: {max_val}")
OUTPUT:
[Link] 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):
l=[]
for i in range(len(L)):
if L[i]!=0:
[Link](i)
return l
L =eval(input("Enter list:"))
indexlist = INDEX_LIST(L)
print("Indices of non-zero elements:", indexlist)
OUTPUT:
8. Write a python program to create a list to store [icode, iname,qty, ppu,tprice] to maintain a stock of a
shop .
# Define the stock list to store information
stock = []
# Function to add an item to the stock list
def add_item(icode, iname, qty, ppu):
tprice = qty * ppu
[Link]([icode, iname, qty, ppu, tprice])
# Example usage
add_item("A001", "Apple", 10, 5)
add_item("B002", "Banana", 20, 2)
add_item("O003", "Orange", 15, 3)
# Print the stock list
for item in stock:
print(f"Code: {item[0]}, Name: {item[1]}, Quantity: {item[2]}, Price per Unit: {item[3]}, Total Price: {item[4]}")
OUTPUT:
9. Write a menu driven program with user defined functions to create a text file [Link], where choices
are:
1-Create text file 2- Generate a frequency list of all the words resent in it
3-Print the line having maximum number of words. 4-Quit
import os
# Function to create a text file
def create_text_file():
with open("[Link]", "w") as f:
content = input("Enter the content for the file: ")
[Link](content)
print("File created successfully.")
# Function to generate a frequency list of all words in the file
def generate_frequency_list():
if not [Link]("[Link]"):
print("File does not exist.")
return
with open("[Link]", "r") as f:
content = [Link]()
words = [Link]()
frequency = {}
for word in words:
frequency[word] = [Link](word, 0) + 1
print("Frequency list of words:", frequency)
# Function to print the line with the maximum number of words
def print_max_words_line():
if not [Link]("[Link]"):
print("File does not exist.")
return
with open("[Link]", "r") as f:
lines = [Link]()
maxline=""
for i in lines:
if len(i)>len(maxline):
maxline=i
print("Line with the maximum number of words:", maxline)
# Main menu function
while True:
print("\nMenu:")
print("1 - Create text file")
print("2 - Generate a frequency list of all the words present in it")
print("3 - Print the line having maximum number of words")
print("4 - Quit")
choice = input("Enter your choice: ")
if choice == '1':
create_text_file()
elif choice == '2':
generate_frequency_list()
elif choice == '3':
print_max_words_line()
elif choice == '4':
break
else:
print("Invalid choice")
OUTPUT:
10. Write a program to remove all the lines that contains character ‘a’ in a file and write them to another
file.
def remove_lines_with_a(input_file, output_file):
l=[]
with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
for line in infile:
if 'a' not in line:
[Link](line)
else:
[Link](line)
with open(input_file,"w") as infile:
for i in l:
[Link](i)
# Example usage
input_file = '[Link]'
output_file = '[Link]'
remove_lines_with_a(input_file, output_file)
print("Lines without 'a' have been written to", output_file)
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
# Function to add an applicant
def add_applicant():
with open("[Link]", "ab") as file:
app_id = input("Enter Applicant ID: ")
name = input("Enter Applicant Name: ")
qualification = input("Enter Qualification: ")
applicant = {'AppID': app_id, 'AName': name, 'Qualification': qualification}
[Link](applicant, file)
print("Applicant added successfully.")
# Function to display all applicants
def display_applicants():
try:
with open("[Link]", "rb") as file:
while True:
try:
applicant = [Link](file)
print(f"ID: {applicant['AppID']}, Name: {applicant['AName']}, Qualification:
{applicant['Qualification']}")
except EOFError:
break
except FileNotFoundError:
print("No applicants found. File does not exist.")
# Function to search for an applicant by ID
def search_applicant():
search_id = input("Enter Applicant ID to search: ")
found = False
try:
with open("[Link]", "rb") as file:
while True:
try:
applicant = [Link](file)
if applicant['AppID'] == search_id:
print(f"ID: {applicant['AppID']}, Name: {applicant['AName']}, Qualification:
{applicant['Qualification']}")
found = True
break
except EOFError:
break
if not found:
print("Applicant not found.")
except FileNotFoundError:
print("No applicants found. File does not exist.")
# Main menu function
def menu():
while True:
print("\nMenu:")
print("1 - Add Applicant")
print("2 - Display All Applicants")
print("3 - Search Applicant by ID")
print("4 - Quit")
choice = input("Enter your choice: ")
if choice == '1':
add_applicant()
elif choice == '2':
display_applicants()
elif choice == '3':
search_applicant()
elif choice == '4':
print("Goodbye!")
break
else:
print("Invalid choice, please try again.")
menu()
OUTPUT:
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:
1-PUSH 2-POP 3-PEEK 4-TRAVERSE
5-QUIT
class Stack:
def __init__(self):
[Link] = []
def push(self, book):
[Link](book)
print("Book pushed successfully.")
def pop(self):
if not [Link]:
print("Stack is empty.")
else:
book = [Link]()
print(f"Popped book: {book}")
def peek(self):
if not [Link]:
print("Stack is empty.")
else:
book = [Link][-1]
print(f"Top book: {book}")
def traverse(self):
if not [Link]:
print("Stack is empty.")
else:
print("Books in stack:")
for book in reversed([Link]):
print(book)
# Main menu function
def menu():
stack = Stack()
while True:
print("\nMenu:")
print("1 - PUSH")
print("2 - POP")
print("3 - PEEK")
print("4 - TRAVERSE")
print("5 - QUIT")
choice = input("Enter your choice: ")
if choice == '1':
book_id = input("Enter Book ID: ")
title = input("Enter Book Title: ")
author = input("Enter Author: ")
publisher = input("Enter Publisher: ")
price = float(input("Enter Price: "))
book = {"BookID": book_id, "BTitle": title, "Author": author, "Publisher": publisher, "Price": price}
[Link](book)
elif choice == '2':
[Link]()
elif choice == '3':
[Link]()
elif choice == '4':
[Link]()
elif choice == '5':
print("Goodbye!")
break
else:
print("Invalid choice, please try again.")
if __name__ == "__main__":
menu()
OUTPUT:
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.
Write a program to input 10 words and push them on to a list ALL.
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 = []
for word in N:
for i in word:
if i in "aeiouAEIOU":
break
else:
[Link](word)
return NoVowel
# Input 10 words and push them to a list ALL
ALL = []
for _ in range(10):
word = input("Enter a word: ")
[Link](word)
# Use the function PUSHNV() to create a stack of words in the list NoVowel
NoVowel = PUSHNV(ALL)
# Pop each word from the list NoVowel and display all popped words
while NoVowel:
print([Link]())
print("Empty Stack")
OUTPUT:
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 = []
for item in SItem:
if SItem[item] > 75:
[Link](item)
count = len(stack)
print("Count of elements pushed onto the stack:", count)
return stack
# Example dictionary of stationary items
SItem = {
'Pen': 50,
'Notebook': 80,
'Eraser': 20,
'Marker': 90,
'Ruler': 30,
'Stapler': 100
# Call the Push function
stack = Push(SItem)
OUTPUT:
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.
create table CLUB(
CoachID int primary key,
CoachName varchar(30) not null,
Age int not null,
Sports varchar(30),
DateOfApp varchar(30),
Pay int,
Sex char(1));
16 Write 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 [Link] as sql
d=[Link](host="localhost",user="root",passwd="mysql",database="GAMES")
cur=[Link]()
t=((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'))
st="insert into CLUB values(%s,'%s',%s,'%s','%s',%s,'%s')"
for i in t:
[Link](st,i)
[Link]()
[Link]()
17 Write 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 [Link] as sql
d=[Link](host="localhost",user="root",passwd="mysql",database="GAMES")
cur=[Link]()
[Link]("select * from CLUB ")
data=[Link]()
[Link]()
OUTPUT:
18. Write SQL statements for following based on table CLUB:
i)List all coaches whose sports is swimming or karate.
ii)List all details sorted in ascending order of age.
iii)Display Sports which have more than one coach.
iv)Display the number of Sports played in Club.
v)List all male Coaches having pay in range of 5000 to 10000.
i.
select CoachName from CLUB where Sports="Swimming" or Sports="Karate";
OUTPUT:
ii.
select * from CLUB order by Age;
OUTPUT:
iii.
select Sports from CLUB group by Sports having count(Sports)>1;
iv.
select * from CLUB where Sex="M" and Pay>=5000 and Pay<=10000;
19 . Write Python interface program using MySQL to increase price by 10% in table CUSTOMER of MYORG
database
import [Link] as sql
d=[Link](host="localhost",user="root",passwd="mysql",database="MYORG")
cur=[Link]()
[Link]("update Customer set Price=Price+Price*0.1")
[Link]()
[Link]()
20. Write a Python interface program using MySQL to delete all those customers whose name contains
Kumar from table CUSTOMER in database MYORG.
import [Link] as sql
d=[Link](host="localhost",user="root",passwd="mysql",database="MYORG")
cur=[Link]()
[Link]("delete from Customer where Name like '%Kumar'")
[Link]()
[Link]()
21.. Create following tables in database MYORG with appropriate data type using SQL commands of
following structure.
Table : Company Table Customer
CID Primary key CustId Primary Key
Name Not Null Name Not Null
City Not Null Price Not Null
Product Name Not Null Qty Check greater than 0
CID Foreign Key
create table Company(
CID int primary key,
Name varchar(30) not null,
City varchar(20) not null,
ProductName varchar(20) not null);
create table Customer(
CustId int primary key,
Name varchar(30) not null,
Price int not null,
Qty int check(Qty>0),
CID int references Company(CID));
22. Write SQL commands to insert following data in above created tables Company and Customer , also list
all data .
Table: Company
CID Name City ProductName
Table:Customer
Sony Delhi TV
CustI Name Price Qt CID
111
d y
222 Nokia Mumba Mobile
101 Rohan 70000 20 222
i
Sharma
333 Onida Delhi TV
102 Deepak 50000 10 666
444 Blackberry Mumba Mobile
Kumar
i
103 Mohan Kumar 30000 5 111
555 Samsung Chennai Mobile
104 Sahil Bansal 35000 3 333
666 Dell Delhi Laptop
105 Neha Soni 25000 7 444
106 Sonal Agarwal 20000 5 333
107 Arjun Singh 50000 15 666
insert into Company values
(111,"Sony","Delhi","TV"),
(222,"Nokia","Mumbai","Mobile"),
(333,"Onida","Delhi","TV"),
(444,"Blackberry","Mumbai","Mobile"),
(555,"Samsung","Chennai","Mobile"),
(666,"Dell","Delhi","Laptop");
insert into Customer values
(101,"Rohan Sharma",70000,20,222),
(102,"Deepak Kumar",50000,10,666),
(103,"Mohan Kumar",30000,5,111),
(104,"Sahil Bansal",35000,3,333),
(105,"Neha Soni",25000,7,444),
(106,"Sonal Agarwal",20000,5,333),
(107,"Arjun Singh",50000,15,666);
select * from Company;
select * from Customer;
OUTPUT:
Q23 Write SQL commands for the following queries based on tables Company and Customer.
Display those company names having price less than 30000.
To increase price by 1000 for those customers whose name starts with ‘S’.
To display Company details in reverse alphabetical order.
To display customer details along with product name and company name of the product.
To display details of companies based in Mumbai or Delhi.
select [Link] from Company right join Customer on [Link]=[Link] where
[Link]<30000;
OUTPUT:
update Customer set Price=Price+1000 where Name like "S%";
select * from Company order by Name desc;
OUTPUT:
select [Link],[Link],[Link],[Link],[Link],[Link],[Link] from Company co right join
Customer cu on [Link]=[Link];
OUTPUT:
select * from Company where City="Mumbai" or City="Delhi";
24. Write Python interface program using MySQL to insert rows in table CLUB in database GAMES.
import [Link] as sql
d=[Link](host="localhost",user="root",passwd="mysql",database="GAMES")
cur=[Link]()
i=int(input("CoachID:"))
n=input("CoachName:")
a=int(input("Age:"))
s=input("Sports:")
da=input("DateOfApp:")
p=int(input("Pay:"))
se=input("Sex:")
st="insert into CLUB values({},'{}',{},'{}','{}',{},'{}')".format(i,n,a,s,da,p,se)
[Link](st)
[Link]()
[Link]()