COMPUTER SCIENCE
REPORT FILE
BY SANSKRITI TIWARI
CLASS 12B
ROLL NO. 11
Q1: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.
while True:
a = input('''Welcome to the simple calculator
Choose from the options below:
- Add for Addition
- Subtract for Subtraction
- Multiply for Multiplication
- Divide for Division
- Any other input to Exit
Enter your choice: ''').lower()
if a == 'add':
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))
print("The sum is:", x + y)
elif a == 'subtract':
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))
print("The difference is:", x - y)
elif a == 'multiply':
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))
print("The product is:", x * y)
elif a == 'divide':
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))
if y != 0:
print("The result of their division is:", x / y)
else:
print("Division by zero is not allowed.")
else:
print("Exit chosen")
break
print("EXIT done")
Q2:Write a program to find sum of series
S=1+x1/2!+x2/3!+…..+xn/(n+1)!
import math
def calculate_series():
x = int(input("Enter the base of the exponent (x): "))
n = int(input("Enter the number of terms in the series (n): "))
s = 1.0 # Starting the series with the first term, which is 1
for i in range(1, n + 1):
s += (x ** i) / math.factorial(i + 1)
print("The sum of the series is:", s)
calculate_series()
Q3:Write a program to print following pattern:
***
*****
*******
n=4
for i in range(n):
# Print spaces
for j in range(n - i - 1):
print(' ', end='')
# Print stars
for k in range(2 * i + 1):
print('*', end='')
# Move to the next line
print()
Q4: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.
r = [10, 20, 15] # Ticket rates for Children, Adults, and Seniors
def bk():
p = [0, 0, 0] # Initialize passenger counts
a = ['Children', 'Adults', 'Seniors'] # Passenger categories
for i in range(len(p)):
p[i] = int(input("Enter number of " + a[i] + ": "))
return p
def cf(p, r):
total = 0
for i in range(len(p)):
total += p[i] * r[i] # Calculate total fare
return total
def pd(p, t, r):
print("\nTicket Details:")
a = ['Children', 'Adults', 'Seniors']
for i in range(len(p)):
print(f"{a[i]}: {p[i]} - ₹{r[i]}/person")
print(f"Total: ₹{t}")
def ps(p, t):
print("\nJourney Summary:")
print(f"Passengers: {sum(p)}")
print(f"Total: ₹{t}")
def m():
print("Welcome to the Ticket Booking System")
p = bk() # Collect passenger details
t = cf(p, r) # Calculate the total cost
pd(p, t, r) # Display ticket details
ps(p, t) # Display journey summary
m()
Q5:-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)):
# Extract the last digit of the element
x = int(L[i]) % 10
# Replace the element based on the condition
if x == 5:
L[i] = 1
else:
L[i] = 0
print("Modified List:", L)
# Input list
L = eval(input("Enter a list of integers: "))
ModifyList(L)
Q6:-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):
a = min(T) # Find the minimum value
b = max(T) # Find the maximum value
print("Maximum value is:", b)
print("Minimum value is:", a)
# Input tuple
T = eval(input("Enter a tuple: "))
minmax(T)
Q7:-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):
# Create a new list to store the modified values
modified_list = []
# Iterate over the list in reverse order
for i in range(len(L) - 1, -1, -1):
if L[i] != 0:
modified_list.append(i) # Replace non-zero element with its
index
# If the element is 0, do not append it to the modified list
(effectively remove it)
# Reverse the modified list to restore original order
modified_list.reverse()
print(modified_list)
# Input list
L = eval(input("Enter a list: "))
INDEX_LIST(L)
Q8:-Write a python program to create a list to store [icode,
iname,qty, ppu,tprice] to maintain a stock of a shop .
s = []
def ai():
n = input("Enter name of the item: ")
q = int(input("Enter quantity: "))
p = int(input("Enter price per unit: "))
tp = q * p
s.append([n, q, p, tp])
print("Item " + n + " added to stock.")
def ds():
print("Current Stock:")
for i in s:
print(" Name: ", i[0], ", Qty: ", str(i[1]), ", PPU: ", str(i[2]), ", Total Price: ", str(i[3]))
while True:
ch = input('''Choose from the options:
1 to add item to stock
2 to display items
any other key for exit
Your choice: ''')
if ch == '1':
ai()
elif ch == '2':
ds()
else:
break
Q9:-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
def cf():
with open("MyFile.txt", "a") as f:
while True:
l = input("Enter the text to write to the file (type 'END' to end):
")
if l.upper() == 'END':
break
f.write(l + '\n') # Fix: write should include newline in the same
string
print("File created successfully!")
def wf():
with open("MyFile.txt", "r") as f:
a = f.read()
e = a.lower()
w = e.split()
v = list(set(w)) # Get unique words
for x in v:
print(x, ": ", str(w.count(x)))
def p():
with open("MyFile.txt", 'r') as file:
ml = "" # Initialize the line with max words
mc = 0 # Initialize max count of words
for l in file:
c = len(l.split()) # Count words in the current line
if c > mc:
mc = c
ml = l.strip() # Store the line with max words
if ml:
print("Line with maximum words:")
print(ml)
else:
print("The file is empty")
while True:
print("Menu:")
print("1. Create text file")
print("2. Generate word frequency")
print("3. Print the line having maximum number of words")
print("4. Exit")
c = input("Enter your choice: ")
if c == "1":
cf()
elif c == "2":
wf()
elif c == "3":
p()
elif c == "4":
break
else:
print("Invalid choice. Please try again.")
Q10:-Write a program to remove all the lines that contains character
‘a’ in a file and write them to another file.
def rma(i, o):
with open(i, "w+") as f:
f.write(input("Enter the text to write to the file: "))
f.seek(0) # Move the file pointer back to the beginning for reading
l = f.readlines()
r = []
for line in l:
if 'a' in line.lower():
r.append(line)
with open(o, 'w') as f:
f.writelines(r)
i = 'i.txt'
o = 'ofile.txt'
rma(i, o)
Q11:-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
def cf():
a = []
while True:
id = int(input("Enter applicant ID (0 to stop): "))
if id == 0:
break
name = input("Enter applicant name: ")
qualification = input("Enter applicant qualification: ")
a.append((id, name, qualification))
with open("applicants.dat", "wb") as f:
pickle.dump(a, f)
print("Applicant file created successfully")
def display():
try:
with open("applicants.dat", "rb") as f:
a = pickle.load(f)
i=1
for applicant in a:
print("Applicant ", i, ":")
print("ID:", applicant[0])
print("Name:", applicant[1])
print("Qualification:", applicant[2])
print()
i += 1
except FileNotFoundError:
print("Applicant file not found")
def search():
try:
with open("applicants.dat", "rb") as f:
a = pickle.load(f)
id = int(input("Enter applicant ID to search: "))
for applicant in a:
if applicant[0] == id:
print("ID:", applicant[0])
print("Name:", applicant[1])
print("Qualification:", applicant[2])
return
print("Applicant not found")
except FileNotFoundError:
print("Applicant file not found")
def modify():
try:
with open("applicants.dat", "rb") as f:
a = pickle.load(f)
id = int(input("Enter applicant ID to modify: "))
for i in range(len(a)):
if a[i][0] == id:
new_name = input("Enter new applicant name: ")
new_qualification = input("Enter new applicant qualification: ")
a[i] = (id, new_name, new_qualification)
with open("applicants.dat", "wb") as f:
pickle.dump(a, f)
print("Applicant modified successfully")
return
print("Applicant not found")
except FileNotFoundError:
print("Applicant file not found")
def delete():
try:
with open("applicants.dat", "rb") as f:
a = pickle.load(f)
id = int(input("Enter applicant ID to delete: "))
for i in range(len(a)):
if a[i][0] == id:
del a[i]
with open("applicants.dat", "wb") as f:
pickle.dump(a, f)
print("Applicant deleted successfully")
return
print("Applicant not found")
except FileNotFoundError:
print("Applicant file not found")
while True:
print("Menu:")
print("1. Create applicant file")
print("2. Display applicants")
print("3. Search applicant")
print("4. Modify applicant")
print("5. Delete applicant")
print("6. Exit")
c = input("Enter your choice: ")
if c == "1":
cf()
elif c == "2":
display()
elif c == "3":
search()
elif c == "4":
modify()
elif c == "5":
delete()
elif c == "6":
break
else:
print("Invalid choice. Please try again.")
Q12:-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
s = []
def push(b):
s.append(b)
def pop():
if len(s) > 0:
s.pop()
def peek():
if len(s) > 0:
print(s[-1])
def traverse():
for b in s:
print(b)
while True:
print("Menu:")
print("1. PUSH")
print("2. POP")
print("3. PEEK")
print("4. TRAVERSE")
print("5. QUIT")
c = int(input("Enter your choice: "))
if c == 1:
id = input("Enter Book ID: ")
t = input("Enter Book Title: ")
a = input("Enter Author: ")
p = input("Enter Publisher: ")
pr = float(input("Enter Price: "))
push((id, t, a, p, pr))
print("Book pushed successfully!")
elif c == 2:
if len(s) > 0:
print("Popped book: ", s[-1])
pop()
else:
print("Stack is empty!")
elif c == 3:
if len(s) > 0:
peek()
else:
print("Stack is empty!")
elif c == 4:
traverse()
elif c == 5:
break
else:
print("Invalid choice. Please try again!")
Q13:-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 PV(w):
nv = []
v = set('aeiouAEIOU')
for x in w:
hv = False
for c in x:
if c in v:
hv = True
break
if not hv:
nv.append(x)
return nv
def m():
aw = []
for i in range(10):
word = input("Enter word " + str(i + 1) + ": ")
aw.append(word)
nv = PV(aw)
print("\nPopping the NoVowel stack:")
while nv:
pw = nv.pop()
print(pw)
if not nv:
print("Empty Stack")
m()
Q14:-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.
s = {}
def push(SItem):
c=0
for item in SItem:
if SItem[item] > 75:
s[len(s) + 1] = {"name": item, "price": SItem[item]}
c += 1
items = []
for i in range(1, len(s) + 1):
items.append(s[i]["name"])
print("Items pushed onto the stack:", items)
print("Count of elements pushed:", c)
SItem = {"Pen": 50, "Pencil": 20, "Book": 100, "Eraser": 30, "Notebook": 80}
push(SItem)
Q16:-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 mysql.connector as s
m=s.connect(host="localhost", user="hehe", passwd="hehe123",
database="games")
if m.is_connected():
print('connection estabilished')
c=m.cursor()
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')
insert = '''INSERT INTO CLUB VALUES(%s, %s, %s, %s, %s, %s, %s)'''
c.executemany(insert,data)
m.commit()
c.execute("select * from club")
d=c.fetchall()
for x in d:
print(x)
Q17:-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 mysql.connector as s
m=s.connect(host="localhost", user="hehe", passwd="hehe123",
database="games")
if m.is_connected():
print('connection estabilished')
c=m.cursor()
a=input("enter sports name")
b="select coachname,age,sex from club where sports='%s'"%a
c.execute(b)
d=c.fetchall()
for i in d:
print(i)
Q18:-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.
Q19:-Write Python interface program using MySQL to increase price
by 10% in table CUSTOMER of MYORG database.
import mysql.connector as s
m=s.connect(host="localhost",user="hehe",passwd="hehe123",data
base="myorg")
if m.is_connected():
print('connection established')
c=m.cursor()
c.execute("update customer set price=price*0.1+price ")
c.execute("select * from customer")
d=c.fetchall()
for i in d:
print(i)
Q20:-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 as s
m=s.connect(host="localhost",user="hehe",passwd="hehe123",data
base="myorg")
if m.is_connected():
print('connection done')
c=m.cursor()
c.execute("delete from customer where name like '%kumar'")
c.execute("select * from customer")
d=c.fetchall()
for i in d:
print(i)
Q21:-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
Q22.
Code-:
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.
Code-:
Q24:Write Python interface program using MySQL to insert rows in
table CLUB in database GAMES.
import mysql.connector as s
m=s.connect(host="localhost", user="hehe", passwd="hehe123",
database="games")
if m.is_connected():
print('connection estabilished')
c=m.cursor()
d = []
c.execute("select * from club")
b=c.fetchall()
for v in b:
print(v)
while True:
i=int(input("enter coach id"))
n = input("name (or 'exit' to finish): ")
if n == 'exit':
break
d.append((i,n, int(input("age: ")), input("sport:
"),input("dateofapp:"),int(input("pay:")),input("gender:")))
c.executemany("INSERT INTO CLUB VALUES(%s, %s,
%s,%s,%s,%s,%s)", d)
m.commit()