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 "Cannot divide by zero"
while True:
print("""
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Quit
""")
choice = int(input("Enter your choice: "))
if choice == 5:
print("Exiting program.")
break
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == 1:
print("Result:", add(num1, num2))
elif choice == 2:
print("Result:", subtract(num1, num2))
elif choice == 3:
print("Result:", multiply(num1, num2))
elif choice == 4:
print("Result:", divide(num1, num2))
else:
print("Invalid choice. Try again.")
2. Write a program to find sum of series
S=1+x1/2!+x2/3!+…..+xn/(n+1)!
x = int(input("Enter value of x: "))
n = int(input("Enter value of n: "))
total = 1
fact = 1
for i in range(1, n+1):
fact *= (i + 1)
total += (x ** i) / fact
print("Sum of series:", total)
3Write a program to print following pattern:
***
*****
*******
n = 4 # Number of rows
for i in range(1, n+1):
print(" " * (n-i) + "*" * (2*i-1))
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
2. End Journey and Show Summary
""")
ch = int(input("Enter your choice: "))
if ch == 1:
age = int(input("Enter passenger's age: "))
if age <= 12:
c_count += 1
total += c_fare
print("Ticket issued: Child, Fare: $5")
elif age <= 59:
a_count += 1
total += a_fare
print("Ticket issued: Adult, Fare: $10")
else:
s_count += 1
total += s_fare
print("Ticket issued: Senior, Fare: $7")
elif ch == 2:
print("Summary of passengers and collection:")
print("Children (0-12):", c_count, "passengers")
print("Adults (13-59):", a_count, "passengers")
print("Seniors (60+):", s_count, "passengers")
print("Total amount collected: $", total)
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
my_list = [15, 23, 5, 42, 25, 37, 45]
ModifyList(my_list)
print("Modified list:", my_list)
OUTPUT
Modified list: [1, 0, 1, 0, 1, 0, 1]
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):
return max(T), min(T)
user_input = eval(input("Enter a tuple of integers: "))
max_value, min_value = MinMax(user_input)
print("Maximum value:", max_value)
print("Minimum value:", min_value)
OUTPUT
Enter a tuple of integers: (5, 3, 9, 1, 7)
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
user_input = eval(input("Enter a list of elements: "))
indexlist = INDEX_LIST(user_input)
print("Indices of non-zero elements:", indexlist)
OUTPUT
Enter a list of elements: [12, 4, 0, 11, 0, 56]
Indices of non-zero elements: [0, 1, 3, 5]
8. Write a python program to create a list to store [icode, iname,qty, ppu,tprice] to maintain a stock of
a shop .
stock = []
icode = input("Enter item code: ")
iname = input("Enter item name: ")
qty = int(input("Enter quantity: "))
ppu = float(input("Enter price per unit: "))
tprice = qty * ppu
stock.append([icode, iname, qty, ppu, tprice])
print("Stock list:", stock)
OUTPUT
Enter item code: A101
Enter item name: Widget
Enter quantity: 10
Enter price per unit: 2.5
Stock list: [['A101', 'Widget', 10, 2.5, 25.0]]
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
3-Print the line having maximum number of words. 4-Quit
import os
def create_file():
with open("MyFile.txt", "w") as f:
content = input("Enter text to write in the file: ")
f.write(content)
def generate_frequency():
if not os.path.exists("MyFile.txt"):
print("File does not exist.")
return
with open("MyFile.txt", "r") as f:
text = f.read()
words = text.split()
frequency = {}
for word in words:
if word in frequency:
frequency[word] += 1
else:
frequency[word] = 1
print("Frequency list:", frequency)
def max_words_line():
if not os.path.exists("MyFile.txt"):
print("File does not exist.")
return
with open("MyFile.txt", "r") as f:
lines = f.readlines()
max_line = ""
max_count = 0
for line in lines:
count = len(line.split())
if count > max_count:
max_count = count
max_line = line.strip()
print("Line with maximum words:", max_line)
while True:
print("""
1. Create text file
2. Generate frequency list
3. Print line with maximum number of words
4. Quit
""")
choice = int(input("Enter your choice: "))
if choice == 1:
create_file()
elif choice == 2:
generate_frequency()
elif choice == 3:
max_words_line()
elif choice == 4:
break
else:
print("Invalid choice. Please try again.")
OUTPUT
Enter text to write in the file:
This is the first line.\n
Here is the second line which is a bit longer.\n
And this is the last line.
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
def remove_lines_with_a(input_file, output_file):
temp_file = "temp.txt"
with open(input_file, "r") as infile:
lines = infile.readlines()
with open(temp_file, "w") as outfile:
for line in lines:
if 'a' in line:
outfile.write(line) # Write lines containing 'a' to output file
else:
# Write lines without 'a' back to temp file
pass
os.rename(temp_file, input_file) # Rename temp file to input file
input_file = "MyFile.txt"
output_file = "FilteredFile.txt"
remove_lines_with_a(input_file, output_file)
print("Lines containing 'a' have been written to", output_file)
print("Original file has been modified.")
OUTPUT
This is the first line.
Another line with a character.
Just a simple line.
No 'a' here.
Final example line with 'a'.
This is the first line.
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():
app_id = int(input("Enter Applicant ID: "))
name = input("Enter Applicant Name: ")
qualification = input("Enter Qualification: ")
applicant = {'AppID': app_id, 'AName': name, 'Qualification': qualification}
with open("Applicants.DAT", "ab") as file:
pickle.dump(applicant, file)
def view_applicants():
if not os.path.exists("Applicants.DAT"):
print("No records found.")
return
with open("Applicants.DAT", "rb") as file:
try:
while True:
applicant = pickle.load(file)
print(applicant) # Directly printing the applicant dictionary
except EOFError:
pass # No more data to read
def search_applicant():
if not os.path.exists("Applicants.DAT"):
print("No records found.")
return
search_id = int(input("Enter Applicant ID to search: "))
found = False
with open("Applicants.DAT", "rb") as file:
try:
while True:
applicant = pickle.load(file)
if applicant['AppID'] == search_id:
print(applicant) # Directly printing the applicant dictionary
found = True
break
except EOFError:
if not found:
print("Applicant not found.")
def delete_applicant():
if not os.path.exists("Applicants.DAT"):
print("No records found.")
return
delete_id = int(input("Enter Applicant ID to delete: "))
found = False
with open("Applicants.DAT", "rb") as file:
applicants = []
try:
while True:
applicant = pickle.load(file)
if applicant['AppID'] != delete_id:
applicants.append(applicant)
else:
found = True
except EOFError:
pass
if found:
with open("Applicants.DAT", "wb") as file:
for applicant in applicants:
pickle.dump(applicant, file)
print("Applicant deleted successfully.")
else:
print("Applicant not found.")
while True:
print("""
1. Add Applicant
2. View All Applicants
3. Search Applicant by ID
4. Delete Applicant by ID
5. Quit
""")
choice = int(input("Enter your choice: "))
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:
print("Invalid choice. Please try again.")
OUTPUT
1. Add Applicant
2. View All Applicants
3. Search Applicant by ID
4. Delete Applicant by ID
5. Quit
Enter your choice: 1
Enter Applicant ID: 101
Enter Applicant Name: Alice
Enter Qualification: B.Sc
1. Add Applicant
2. View All Applicants
3. Search Applicant by ID
4. Delete Applicant by ID
5. Quit
Enter your choice: 2
{'AppID': 101, 'AName': 'Alice', 'Qualification': 'B.Sc'}
1. Add Applicant
2. View All Applicants
3. Search Applicant by ID
4. Delete Applicant by ID
5. Quit
Enter your choice: 3
Enter Applicant ID to search: 101
{'AppID': 101, 'AName': 'Alice', 'Qualification': 'B.Sc'}
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
stack = []
def push():
book_id = input("Enter BookID: ")
title = input("Enter Book Title: ")
author = input("Enter Author: ")
publisher = input("Enter Publisher: ")
price = input("Enter Price: ")
book = {
'BookID': book_id,
'BTitle': title,
'Author': author,
'Publisher': publisher,
'Price': price
stack.append(book)
print("Book pushed into stack.")
def pop():
if len(stack) == 0:
print("Stack is empty. Nothing to pop.")
else:
book = stack.pop()
print("Popped Book:", book)
def peek():
if len(stack) == 0:
print("Stack is empty.")
else:
print("Top of the Stack:", stack[-1])
def traverse():
if len(stack) == 0:
print("Stack is empty.")
else:
print("Books in Stack:")
for book in stack:
print(book)
while True:
print("""
1. PUSH
2. POP
3. PEEK
4. TRAVERSE
5. QUIT
""")
choice = int(input("Enter your choice: "))
if choice == 1:
push()
elif choice == 2:
pop()
elif choice == 3:
peek()
elif choice == 4:
traverse()
elif choice == 5:
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
OUTPUT
1. PUSH
2. POP
3. PEEK
4. TRAVERSE
5. QUIT
Enter your choice: 1
Enter BookID: B001
Enter Book Title: Python Programming
Enter Author: John Smith
Enter Publisher: TechBooks
Enter Price: 25.99
Book pushed into stack.
1. PUSH
2. POP
3. PEEK
4. TRAVERSE
5. QUIT
Enter your choice: 4
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
Enter your choice: 5
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.
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 = []
vowels = 'aeiouAEIOU'
for word in n:
if all(char not in vowels for char in word):
novowel.append(word)
return novowel
all_words = eval(input("Enter 10 words in a list like ['word1', 'word2', ...]: "))
novowel = pushnv(all_words)
while novowel:
print("Popped word:", novowel.pop())
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']
Popped word: xyz
Popped word: cry
Popped word: try
Popped word: fly
Popped word: rhythm
Popped word: sky
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
for name, price in sitem.items():
if price > 75:
stack.append(name)
count += 1
return stack, count
sitem = eval(input("Enter stationary items as a dictionary like {'item1': price1, 'item2': price2, ...}: "))
stack, count = push(sitem)
print("Items pushed onto the stack:", stack)
print("Count of elements pushed:", count)
OUTPUT
Enter stationary items as a dictionary like {'item1': price1, 'item2': price2, ...}: {'pen': 50, 'notebook': 100,
'pencil': 20, 'marker': 80}
Items pushed onto the stack: ['notebook', 'marker']
Count of elements pushed: 2
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(50) NOT NULL,
Age INT NOT NULL,
Sports VARCHAR(30),
DateOfApp DATE,
Pay DECIMAL(10, 2),
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
# Connect to the MySQL database
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="GAMES"
cursor = conn.cursor()
# Insert multiple rows into CLUB table
query = "INSERT INTO CLUB (CoachID, CoachName, Age, Sports, DateOfApp, Pay, Sex) VALUES (%s, %s,
%s, %s, %s, %s, %s)"
data = [
(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')
cursor.executemany(query, data)
# Commit the transaction
conn.commit()
# Close the connection
cursor.close()
conn.close()
print("Rows inserted successfully!")
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
# Connect to the MySQL database
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="GAMES"
cursor = conn.cursor()
# Get sport name input from the user
sport = input("Enter the sport name to retrieve coach details: ")
# SQL query to retrieve coach details based on the sport name
query = "SELECT * FROM CLUB WHERE Sports = %s"
cursor.execute(query, (sport,))
# Fetch and display the results
results = cursor.fetchall()
if results:
for row in results:
print("CoachID:", row[0], "Name:", row[1], "Age:", row[2], "Sport:", row[3], "DateOfApp:", row[4],
"Pay:", row[5], "Sex:", row[6])
else:
print("No coach found for the given sport.")
# Close the connection
cursor.close()
conn.close()
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) List all coaches whose sports is swimming or karate:
SELECT * FROM CLUB WHERE Sports IN ('Swimming', 'Karate');
ii) List all details sorted in ascending order of age:
SELECT * FROM CLUB ORDER BY Age ASC;
iii) Display Sports which have more than one coach:
SELECT Sports, COUNT(*) AS CoachCount
FROM CLUB
GROUP BY Sports
HAVING COUNT(*) > 1;
iv) Display the number of Sports played in the Club:
SELECT COUNT(DISTINCT Sports) AS NumberOfSports FROM CLUB;
v) List all male Coaches having pay in range of 5000 to 10000:
SELECT * FROM CLUB WHERE Sex = 'M' AND Pay BETWEEN 5000 AND 10000;
19.Write Python interface program using MySQL to increase price by 10% in table CUSTOMER of MYORG
database
import mysql.connector
# Connect to the MySQL database
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="MYORG"
cursor = conn.cursor()
# SQL query to increase price by 10%
query = "UPDATE CUSTOMER SET Price = Price * 1.10"
cursor.execute(query)
# Commit the changes
conn.commit()
# Print success message
print("Price increased by 10% for all customers.")
# Close the connection
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
# Connect to the MySQL database
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="MYORG"
cursor = conn.cursor()
# SQL query to delete customers whose name contains 'Kumar'
query = "DELETE FROM CUSTOMER WHERE Name LIKE '%Kumar%'"
cursor.execute(query)
# Commit the changes
conn.commit()
# Print success message
print("Deleted all customers whose name contains 'Kumar'.")
# Close the connection
cursor.close()
conn.close()
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(100) NOT NULL,
City VARCHAR(100) NOT NULL,
ProductName VARCHAR(100) NOT NULL
);
CREATE TABLE Customer (
CustId INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Price DECIMAL(10, 2) NOT NULL,
Qty INT CHECK (Qty > 0),
CID INT,
FOREIGN KEY (CID) 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
Sony Delhi TV
111
222 Nokia Mumba Mobile
i
333 Onida Delhi TV
444 Blackberry Mumba Mobile
i
555 Samsung Chennai Mobile
666 Dell Delhi Laptop
Table:Customer
CustI Name Price Qty CID
d
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
INSERT INTO Company (CID, Name, City, ProductName) 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 (CustId, Name, Price, Qty, CID) 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;
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.
i) Display those company names having price less than 30000.
SELECT C.Name
FROM Company C
JOIN Customer CU ON C.CID = CU.CID
WHERE CU.Price < 30000;
ii) To increase price by 1000 for those customers whose name starts with ‘S’.
UPDATE Customer
SET Price = Price + 1000
WHERE Name LIKE 'S%';
iii) To display Company details in reverse alphabetical order.
SELECT *
FROM Company
ORDER BY Name DESC;
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;
v) To display details of companies based in Mumbai or Delhi.
SELECT *
FROM Company
WHERE City IN ('Mumbai', 'Delhi');
24. Write Python interface program using MySQL to insert rows in table CLUB
in database GAMES
import mysql.connector as mysql
# Connect to the MySQL database
db = mysql.connect(
host="localhost",
user="root", # Replace with your MySQL username
password="password", # Replace with your MySQL password
database="GAMES" # The database where the CLUB table exists
)
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): ")
# SQL query to insert data into the CLUB table
query = "INSERT INTO CLUB (CoachID, CoachName, Age, Sports, DateOfApp,
Pay, Sex) VALUES (%s, %s, %s, %s, %s, %s, %s)"
values = (coach_id, name, age, sport, date_of_app, pay, sex)
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}")
# Calling the function to insert data
insert_club()
# Close the cursor and connection
cursor.close()
db.close()