0% found this document useful (0 votes)
3 views28 pages

Ayush Report File

The document contains a series of programming tasks and their corresponding solutions in Python. The tasks include mathematical calculations, series summation, pattern printing, ticket pricing based on age, list modification, tuple min-max finding, index listing of non-zero elements, stock management, text file operations, line filtering, applicant management in a binary file, and stack implementation for book details. Each task is accompanied by code snippets and sample outputs demonstrating the functionality.

Uploaded by

ayushnig787
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views28 pages

Ayush Report File

The document contains a series of programming tasks and their corresponding solutions in Python. The tasks include mathematical calculations, series summation, pattern printing, ticket pricing based on age, list modification, tuple min-max finding, index listing of non-zero elements, stock management, text file operations, line filtering, applicant management in a binary file, and stack implementation for book details. Each task is accompanied by code snippets and sample outputs demonstrating the functionality.

Uploaded by

ayushnig787
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

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.

Answer

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 "Division by zero is undefined."
else:
return a / b

def main():
while True:
print("\nSelect an operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Quit")

choice = input("Enter choice (1/2/3/4/5): ")

if choice == '5':
print("Exiting the program. Goodbye!")
break

if choice in ('1', '2', '3', '4'):


try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

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

2. Write a program to find sum of series S=1+x1/2!+x2/3!+…..+xn/(n+1)!

Answer:

import math

def series_sum(x, n):


sum_series = 1
for i in range(1, n + 1):
term = (x ** i) / math.factorial(i + 1)
sum_series += term
return sum_series

x = int(input("Enter the value of x: "))


n = int(input("Enter the value of n: "))
print("Sum of the series:", series_sum(x, n))

Output:

Enter the value of x: 2


Enter the value of n: 3
Sum of the series: 1.75

3) Write a program to print the following pattern:

*
***
*****
*******

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:

Enter the number of rows: 4


*
***
*****
*******

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.")

total_collection = sum(price for _, price in passengers)


age_groups = {'children': 0, 'adults': 0, 'seniors': 0}
for age, _ in passengers:
if age < 5:
continue
elif age <= 18:
age_groups['children'] += 1
elif age <= 60:
age_groups['adults'] += 1
else:
age_groups['seniors'] += 1

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:

Enter age of passenger (or type 'done' to finish): 10


Ticket price for age 10 is: 50
Enter age of passenger (or type 'done' to finish): 30
Ticket price for age 30 is: 100
Enter age of passenger (or type 'done' to finish): 65
Ticket price for age 65 is: 80
Enter age of passenger (or type 'done' to finish): done

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

L = [25, 30, 45, 60, 75, 80]


print("Modified List:", ModifyList(L))

Output:

Modified List: [1, 0, 1, 0, 1, 0]

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:

Minimum Value: 1, Maximum Value: 9


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]

Answer:

def INDEX_LIST(L):
indexlist = [index for index, value in enumerate(L) if value != 0]
return indexlist

L = [12, 4, 0, 11, 0, 56]


indexlist = INDEX_LIST(L)
print("Index List of Non-Zero Elements:", indexlist)

Output:

Index List 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 .

Answer:

def create_stock_item(icode, iname, qty, ppu):

tprice = qty * ppu

return [icode, iname, qty, ppu, tprice]

stock = []

stock.append(create_stock_item(101, "Soap", 50, 20))

stock.append(create_stock_item(102, "Shampoo", 30, 100))

stock.append(create_stock_item(103, "Toothpaste", 40, 30))

print("Stock List:")

for item in stock:

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

3-Print the line having maximum number of words. 4-Quit

Answer:

def create_file():

with open("MyFile.txt", "w") as file:

content = input("Enter text to write to the file (type 'done' to finish):\n")

while content.lower() != 'done':

file.write(content + "\n")

content = input()

def word_frequency():

with open("MyFile.txt", "r") as file:

content = file.read().split()

frequency = {}

for word in content:

frequency[word] = frequency.get(word, 0) + 1

print("Word Frequency:", frequency)

def max_word_line():

with open("MyFile.txt", "r") as file:

lines = file.readlines()

max_line = max(lines, key=lambda line: len(line.split()))


print("Line with maximum words:", max_line.strip())

def main():

while True:

print("\n1. Create text file")

print("2. Generate a frequency list of words")

print("3. Print line with maximum words")

print("4. Quit")

choice = input("Enter choice: ")

if choice == '1':

create_file()

elif choice == '2':

word_frequency()

elif choice == '3':

max_word_line()

elif choice == '4':

print("Exiting program.")

break

else:

print("Invalid choice. Please try again.")

if __name__ == "__main__":

main()

Output:

1. Create text file

2. Generate a frequency list of words

3. Print line with maximum words

4. Quit

Enter choice: 1
Enter text to write to the file (type 'done' to finish):

Hello world

Python programming

done

Enter choice: 2

Word Frequency: {'Hello': 1, 'world': 1, 'Python': 1, 'programming': 1}

Enter choice: 3

Line with maximum words: Python programming

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:

def remove_lines_with_a(input_file, output_file):


with open(input_file, "r") as file:
lines = file.readlines()

with open(output_file, "w") as file:


for line in lines:
if 'a' not in line.lower():
file.write(line)

# Remove lines containing 'a' from MyFile.txt and write to FilteredFile.txt


remove_lines_with_a("MyFile.txt", "FilteredFile.txt")
print("Lines without 'a' have been written to FilteredFile.txt")

Output:

Lines without 'a' have been written to FilteredFile.txt

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 add_applicant(app_file, app_id, name, qualification):


applicant = {'AppID': app_id, 'AName': name, 'Qualification': qualification}
with open(app_file, "ab") as file:
pickle.dump(applicant, file)

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")

choice = input("Enter choice: ")


if choice == '1':
app_id = input("Enter Applicant ID: ")
name = input("Enter Applicant Name: ")
qualification = input("Enter Qualification: ")
add_applicant(app_file, app_id, name, qualification)
elif choice == '2':
print("Applicants List:")
display_applicants(app_file)
elif choice == '3':
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")

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:

1-PUSH 2-POP 3-PEEK 4-TRAVERSE

5-QUIT

Answer:

stack = []

def push(book):

stack.append(book)

print("Book pushed to stack.")

def pop():

if stack:

return stack.pop()

else:

return "Stack is empty."

def peek():

if stack:
return stack[-1]

else:

return "Stack is empty."

def traverse():

if stack:

for book in 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")

choice = input("Enter 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, "Title": title, "Author": author, "Publisher": publisher, "Price": price}

push(book)

elif choice == '2':

print("Popped book:", pop())


elif choice == '3':

print("Top book:", peek())

elif choice == '4':

print("Stack contents:")

traverse()

elif choice == '5':

print("Exiting program.")

break

else:

print("Invalid choice. Please try again.")

if __name__ == "__main__":

main()

Output:

1. PUSH

2. POP

3. PEEK

4. TRAVERSE

5. QUIT

Enter choice: 1

Enter Book ID: 101

Enter Book Title: Python Programming

Enter Author: John Doe

Enter Publisher: TechBooks

Enter Price: 499.99

Book pushed to stack.

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.

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”.

Answer:

def PUSHNV(N):

NoVowel = []

for word in N:

if not any(char in 'aeiouAEIOU' for char in word):

NoVowel.append(word)

return NoVowel

def main():

ALL = []

for i in range(10):

word = input(f"Enter word {i + 1}: ")

ALL.append(word)
NoVowel = PUSHNV(ALL)

print("\nWords without vowels (stack NoVowel):")

while NoVowel:

print("Popped word:", NoVowel.pop())

if not NoVowel:

print("Empty Stack")

if __name__ == "__main__":

main()

Output:

Enter word 1: sky

Enter word 2: fly

Enter word 3: apple

Enter word 4: sun

Enter word 5: try

Enter word 6: cry

Enter word 7: moon

Enter word 8: star

Enter word 9: why

Enter word 10: yes

Words without vowels (stack NoVowel):

Popped word: try

Popped word: cry

Popped word: why

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:

Items pushed onto the stack: 3


Stack contents: ['Notebook', 'Marker', 'Binder']

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:

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)
);

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():

# Establishing the connection

conn = mysql.connector.connect(

host="localhost",

user="your_username",

password="your_password",

database="GAMES"

cursor = conn.cursor()

# Insert statements

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, 'Basketball', '2005-01-01', 15000, 'M'),

(5, 'Zubin', 36, 'Swimming', '1998-02-24', 7500, 'M'),

(6, 'Ketaki', 33, 'Swimming', '2001-12-23', 8000, 'F')

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()

print("Data inserted successfully.")

cursor.close()

conn.close()

insert_coach_data()

Output:

Data inserted successfully.

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):

# Establishing the connection

conn = mysql.connector.connect(

host="localhost",
user="your_username",

password="your_password",

database="GAMES"

cursor = conn.cursor()

# Query to retrieve data based on sport name

query = "SELECT * FROM CLUB WHERE Sports = %s"

cursor.execute(query, (sport_name,))

results = cursor.fetchall()

if results:

print("Coach Details:")

for row in results:

print(row)

else:

print("No coaches found for the specified sport.")

cursor.close()

conn.close()

# Get sport name from user and retrieve data

sport_name = input("Enter the sport name: ")

retrieve_coaches_by_sport(sport_name)

Output:

Enter the sport name: Karate

Coach Details:

(1, 'Kukreja', 35, 'Karate', '1996-03-27', 10000, 'M')


(2, 'Ravina', 34, 'Karate', '1998-01-20', 12000, 'F')

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 coaches whose sports are swimming or karate:

SELECT * FROM CLUB WHERE Sports = 'Swimming' OR Sports = 'Karate';

 SQL to list all details sorted in ascending order of age:

SELECT * FROM CLUB ORDER BY Age ASC;

 SQL to display sports that have more than one coach:

SELECT Sports FROM CLUB GROUP BY Sports HAVING COUNT(CoachID) > 1;

 SQL to display the number of sports played in the club:

SELECT COUNT(DISTINCT Sports) AS NumberOfSports FROM CLUB;

 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()

# Update query to increase price by 10%


query = "UPDATE CUSTOMER SET Price = Price * 1.10"
cursor.execute(query)
conn.commit()

print("Prices increased by 10% successfully.")


cursor.close()
conn.close()

# Run the function to increase prices


increase_price()

Output:

Prices increased by 10% successfully.

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():

# Establishing the connection

conn = mysql.connector.connect(

host="localhost",

user="your_username",

password="your_password",

database="MYORG"

)
cursor = conn.cursor()

# Delete query to remove customers with "Kumar" in their name

query = "DELETE FROM CUSTOMER WHERE Name LIKE '%Kumar%'"

cursor.execute(query)

conn.commit()

print("Customers with 'Kumar' in their name have been deleted.")

cursor.close()

conn.close()

# Run the function to delete customers

delete_customers_with_kumar()

Output:

Customers with 'Kumar' in their name have been deleted.

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:

CREATE TABLE Company (


CID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
City VARCHAR(50) NOT NULL,
ProductName VARCHAR(50) NOT NULL
);

CREATE TABLE Customer (


CustId INT PRIMARY KEY,
Name VARCHAR(50) 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 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:

-- Insert data into Company table


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 data into Customer table


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);

-- List all data in Company table


SELECT * FROM Company;

-- List all data in Customer table


SELECT * FROM Customer;

23) Write SQL commands for the following queries based on tables Company and
Customer:

Display those company names with a price less than 30000.

Increase the price by 1000 for those customers whose name starts with ‘S’.

Display company details in reverse alphabetical order.

Display customer details along with product name and company name of the product.

Display details of companies based in Mumbai or Delhi.

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

SET Price = Price + 1000


WHERE Name LIKE 'S%';

SQL to display company details in reverse alphabetical order:

SELECT * FROM Company

ORDER BY Name DESC;

SQL to display customer details along with product name and company name of the product:

SELECT Customer.*, Company.ProductName, Company.Name AS CompanyName

FROM Customer

JOIN Company ON Customer.CID = Company.CID;

SQL to display details of companies based in Mumbai or Delhi:

SELECT * FROM Company

WHERE City IN ('Mumbai', 'Delhi');

24) Write a Python interface program using MySQL to insert rows in the CLUB table in the GAMES
database.

Answer:

import mysql.connector

def insert_club_data(coach_id, coach_name, age, sports, date_of_app, pay, sex):

# Establishing the connection

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()

print("Data inserted successfully.")

cursor.close()

conn.close()

# Example data insertion

insert_club_data(1, 'Kukreja', 35, 'Karate', '1996-03-27', 10000, 'M')

Output:

Data inserted successfully.

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()

# Update query to increase price by 10%


query = "UPDATE CUSTOMER SET Price = Price * 1.10"
cursor.execute(query)
conn.commit()

print("Prices increased by 10% successfully.")


cursor.close()
conn.close()

# Run the function to increase prices


increase_price()

Output:

Prices increased by 10% successfully.

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()

# Delete query to remove customers with "Kumar" in their name


query = "DELETE FROM CUSTOMER WHERE Name LIKE '%Kumar%'"
cursor.execute(query)
conn.commit()

print("Customers with 'Kumar' in their name have been deleted.")


cursor.close()
conn.close()

# Run the function to delete customers


delete_customers_with_kumar()

Output:

Customers with 'Kumar' in their name have been deleted.

You might also like