Ayush Report File
Ayush Report File
Answer
def main():
while True:
print("\nSelect an operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Quit")
if choice == '5':
print("Exiting the program. Goodbye!")
break
if choice == '1':
print(f"The result of addition is: {add(num1, num2)}")
elif choice == '2':
print(f"The result of subtraction is: {subtract(num1, num2)}")
elif choice == '3':
print(f"The result of multiplication is: {multiply(num1, num2)}")
elif choice == '4':
print(f"The result of division is: {divide(num1, num2)}")
except ValueError:
print("Invalid input! Please enter valid integers.")
else:
print("Invalid choice! Please select a valid option.")
if __name__ == "__main__":
main()
Output:
Select an operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Quit
Enter choice (1/2/3/4/5): 1
Enter first number: 10
Enter second number: 5
The result of addition is: 15
Select an operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Quit
Enter choice (1/2/3/4/5): 5
Answer:
import math
Output:
*
***
*****
*******
Answer:
def print_pattern(n):
for i in range(n):
print(" " * (n - i - 1) + "*" * (2 * i + 1))
n = int(input("Enter the number of rows: "))
print_pattern(n)
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.
Answer:
def calculate_ticket_price(age):
if age < 5:
return 0 # Free ticket for age < 5
elif age <= 18:
return 50 # Ticket price for children
elif age <= 60:
return 100 # Ticket price for adults
else:
return 80 # Ticket price for senior citizens
def main():
passengers = []
while True:
age = input("Enter age of passenger (or type 'done' to finish): ")
if age.lower() == 'done':
break
try:
age = int(age)
price = calculate_ticket_price(age)
passengers.append((age, price))
print(f"Ticket price for age {age} is: {price}")
except ValueError:
print("Invalid input. Please enter a valid age.")
print("\nJourney Summary:")
print(f"Children: {age_groups['children']}")
print(f"Adults: {age_groups['adults']}")
print(f"Seniors: {age_groups['seniors']}")
print(f"Total collection: {total_collection}")
if __name__ == "__main__":
main()
Output:
Journey Summary:
Children: 1
Adults: 1
Seniors: 1
Total collection: 230
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.
Answer:
def ModifyList(L):
for i in range(len(L)):
if L[i] % 10 == 5:
L[i] = 1
else:
L[i] = 0
return L
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
Answer:
def MinMax(T):
min_value = min(T)
max_value = max(T)
return min_value, max_value
T = (3, 5, 1, 8, 6, 9)
min_val, max_val = MinMax(T)
print(f"Minimum Value: {min_val}, Maximum Value: {max_val}")
Output:
Answer:
def INDEX_LIST(L):
indexlist = [index for index, value in enumerate(L) if value != 0]
return 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 .
Answer:
stock = []
print("Stock List:")
print(f"Item Code: {item[0]}, Name: {item[1]}, Quantity: {item[2]}, Price per unit: {item[3]},
Total Price: {item[4]}")
Output:
Stock List:
Item Code: 101, Name: Soap, Quantity: 50, Price per unit: 20, Total Price: 1000
Item Code: 102, Name: Shampoo, Quantity: 30, Price per unit: 100, Total Price: 3000
Item Code: 103, Name: Toothpaste, Quantity: 40, Price per unit: 30, Total Price: 1200
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
Answer:
def create_file():
file.write(content + "\n")
content = input()
def word_frequency():
content = file.read().split()
frequency = {}
frequency[word] = frequency.get(word, 0) + 1
def max_word_line():
lines = file.readlines()
def main():
while True:
print("4. Quit")
if choice == '1':
create_file()
word_frequency()
max_word_line()
print("Exiting program.")
break
else:
if __name__ == "__main__":
main()
Output:
4. Quit
Enter choice: 1
Enter text to write to the file (type 'done' to finish):
Hello world
Python programming
done
Enter choice: 2
Enter choice: 3
Enter choice: 4
Exiting program.
10) Write a program to remove all the lines that contains character ‘a’ in a file and write them
to another file.
Answer:
Output:
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)
Answer:
import pickle
def display_applicants(app_file):
with open(app_file, "rb") as file:
try:
while True:
applicant = pickle.load(file)
print(applicant)
except EOFError:
pass
def main():
app_file = "Applicants.DAT"
while True:
print("\n1. Add Applicant")
print("2. Display Applicants")
print("3. Quit")
if __name__ == "__main__":
main()
Output:
1. Add Applicant
2. Display Applicants
3. Quit
Enter choice: 1
Enter Applicant ID: 101
Enter Applicant Name: John Doe
Enter Qualification: MSc
Enter choice: 2
Applicants List:
{'AppID': '101', 'AName': 'John Doe', 'Qualification': 'MSc'}
Enter choice: 3
Exiting program.
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
Answer:
stack = []
def push(book):
stack.append(book)
def pop():
if stack:
return stack.pop()
else:
def peek():
if stack:
return stack[-1]
else:
def traverse():
if stack:
print(book)
else:
print("Stack is empty.")
def main():
while True:
print("\n1. PUSH")
print("2. POP")
print("3. PEEK")
print("4. TRAVERSE")
print("5. QUIT")
if choice == '1':
book = {"BookID": book_id, "Title": title, "Author": author, "Publisher": publisher, "Price": price}
push(book)
print("Stack contents:")
traverse()
print("Exiting program.")
break
else:
if __name__ == "__main__":
main()
Output:
1. PUSH
2. POP
3. PEEK
4. TRAVERSE
5. QUIT
Enter choice: 1
Enter choice: 3
Top book: {'BookID': '101', 'Title': 'Python Programming', 'Author': 'John Doe', 'Publisher':
'TechBooks', 'Price': 499.99}
Enter choice: 4
Stack contents:
{'BookID': '101', 'Title': 'Python Programming', 'Author': 'John Doe', 'Publisher': 'TechBooks', 'Price':
499.99}
Enter choice: 5
Exiting program.
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”.
Answer:
def PUSHNV(N):
NoVowel = []
for word in N:
NoVowel.append(word)
return NoVowel
def main():
ALL = []
for i in range(10):
ALL.append(word)
NoVowel = PUSHNV(ALL)
while NoVowel:
if not NoVowel:
print("Empty Stack")
if __name__ == "__main__":
main()
Output:
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}.
Answer:
stack = []
def Push(SItem):
count = 0
for item, price in SItem.items():
if price > 75:
stack.append(item)
count += 1
print(f"Items pushed onto the stack: {count}")
stationery_items = {
"Pen": 50,
"Notebook": 100,
"Eraser": 20,
"Marker": 80,
"Ruler": 40,
"Binder": 120
}
Push(stationery_items)
print("Stack contents:", stack)
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.
Answer:
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'
Answer:
import mysql.connector
def insert_coach_data():
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="GAMES"
cursor = conn.cursor()
# Insert statements
data = [
query = "INSERT INTO CLUB (CoachID, CoachName, Age, Sports, DateOfApp, Pay, Sex) VALUES (%s,
%s, %s, %s, %s, %s, %s)"
cursor.executemany(query, data)
conn.commit()
cursor.close()
conn.close()
insert_coach_data()
Output:
17 ) Write a Python interface program using MySQL to retrieve details of coaches as per the sport
name input by the user from the CLUB table in the GAMES database.
Answer:
import mysql.connector
def retrieve_coaches_by_sport(sport_name):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="GAMES"
cursor = conn.cursor()
cursor.execute(query, (sport_name,))
results = cursor.fetchall()
if results:
print("Coach Details:")
print(row)
else:
cursor.close()
conn.close()
retrieve_coaches_by_sport(sport_name)
Output:
Coach Details:
18) Write SQL statements for the following queries based on the CLUB table:
List all coaches whose sports are swimming or karate.
List all details sorted in ascending order of age.
Display sports that have more than one coach.
Display the number of sports played in the club.
List all male coaches with pay in the range of 5000 to 10000.
Answer:
SQL to list all male coaches with pay in the range of 5000 to 10000:
SELECT * FROM CLUB WHERE Sex = 'M' AND Pay BETWEEN 5000 AND 10000;
19) Write a Python interface program using MySQL to increase the price by 10% in the
CUSTOMER table of the MYORG database.
Answer:
import mysql.connector
def increase_price():
# Establishing the connection
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="MYORG"
)
cursor = conn.cursor()
Output:
20) Write a Python interface program using MySQL to delete all those customers whose name
contains "Kumar" from the CUSTOMER table in the MYORG database.
Answer:
import mysql.connector
def delete_customers_with_kumar():
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="MYORG"
)
cursor = conn.cursor()
cursor.execute(query)
conn.commit()
cursor.close()
conn.close()
delete_customers_with_kumar()
Output:
21) Create the following tables in the MYORG database with appropriate data types using SQL
commands based on the following structure:
• Table: Company
o CID Primary Key
o Name Not Null
o City Not Null
o ProductName Not Null
• Table: Customer
o CustId Primary Key
o Name Not Null
o Price Not Null
o Qty Check greater than 0
o CID Foreign Key (refers to Company table)
Answer:
22) Write SQL commands to insert the following data in the Company and Customer tables
created above, and list all data.
Company Data:
CID: 111, Name: Sony, City: Delhi, ProductName: TV
CID: 222, Name: Nokia, City: Mumbai, ProductName: Mobile
CID: 333, Name: Onida, City: Delhi, ProductName: TV
CID: 444, Name: Blackberry, City: Mumbai, ProductName: Mobile
CID: 555, Name: Samsung, City: Chennai, ProductName: Mobile
CID: 666, Name: Dell, City: Delhi, ProductName: Laptop
Customer Data:
CustId: 101, Name: Rohan Sharma, Price: 70000, Qty: 20, CID: 222
CustId: 102, Name: Deepak Kumar, Price: 50000, Qty: 10, CID: 666
CustId: 103, Name: Mohan Kumar, Price: 30000, Qty: 5, CID: 111
CustId: 104, Name: Sahil Bansal, Price: 35000, Qty: 3, CID: 333
CustId: 105, Name: Neha Soni, Price: 25000, Qty: 7, CID: 444
CustId: 106, Name: Sonal Agarwal, Price: 20000, Qty: 5, CID: 333
CustId: 107, Name: Arjun Singh, Price: 50000, Qty: 15, CID: 666
Answer:
23) Write SQL commands for the following queries based on tables Company and
Customer:
Increase the price by 1000 for those customers whose name starts with ‘S’.
Display customer details along with product name and company name of the product.
Answer:
SQL to display those company names with a price less than 30000:
SELECT Company.Name
FROM Company
JOIN Customer ON Company.CID = Customer.CID
WHERE Customer.Price < 30000;
SQL to increase the price by 1000 for those customers whose name starts with ‘S’:
UPDATE Customer
SQL to display customer details along with product name and company name of the product:
FROM Customer
24) Write a Python interface program using MySQL to insert rows in the CLUB table in the GAMES
database.
Answer:
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="GAMES"
cursor = conn.cursor()
# Insert statement
query = "INSERT INTO CLUB (CoachID, CoachName, Age, Sports, DateOfApp, Pay, Sex)
VALUES (%s, %s, %s, %s, %s, %s, %s)"
data = (coach_id, coach_name, age, sports, date_of_app, pay, sex)
cursor.execute(query, data)
conn.commit()
cursor.close()
conn.close()
Output:
25) Write a Python interface program using MySQL to increase the price by 10% in the
CUSTOMER table of the MYORG database.
Answer:
import mysql.connector
def increase_price():
# Establishing the connection
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="MYORG"
)
cursor = conn.cursor()
Output:
26) Write a Python interface program using MySQL to delete all those customers whose name
contains "Kumar" from the CUSTOMER table in the MYORG database.
Answer:
import mysql.connector
def delete_customers_with_kumar():
# Establishing the connection
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="MYORG"
)
cursor = conn.cursor()
Output: