Shravan Nagendran Grade 12 Practical File Computer Science
Shravan Nagendran Grade 12 Practical File Computer Science
SUBMITTED BY:
Date :
(OR)
(OR)
Table: CUSTOMER
CUSTID CID NAME PRICE QTY
C01 222 ROHIT SHARMA 70000 20
C02 666 DEEPIKA KUMARI 50000 10
C03 111 MOHAN KUMAR 30000 5
C04 555 RADHA MOHAN 30000 11
Ans:
Table: SALES
PROD_ID QTY_SOLD QUARTER
P002 4 1
P003 2 2
P001 3 2
P004 2 1
Table: FLIGHT
FNO START END F_DATE FARE
F101 MUMBAI CHENNAI 2021-12-25 4500.00
F102 MUMBAI BENGALURU 2021-11-20 4000.00
F103 DELHI CHENNAI 2021-12-10 5500.00
F104 KOLKATA MUMBAI 2021-12-20 4500.00
F105 DELHI BENGALURU 2021-01-15 5000.00
(ii) SELECT GENDER, COUNT(*) "TOTAL NUMBER" FROM PASSENGER GROUP BY GENDER;
CBSE-2024 (ii)
(Sumit wants to write a code in Python to display all the details of the
passengers from the table flight in MySQL database, Travel. The table contains
the following attributes:
F_code: Flight code (String)
F_name: Name of flight (String)
Source: Departure city of flight (String)
Destination: Destination city of flight (String)
Consider the following to establish connectivity between Python and MySQL:
• Username: root
• Password: airplane
• Host: localhost
Program:
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",passwd='airplane',
database='Travel')
cur=con.cursor()
cur.execute("select * from flight")
Records=cur.fetchall()
count=cur.rowcount
print("Total number of rows = : ", count)
for row in Records:
print(row)
con.close()
Python-MySQL Connectivity
CBSE-2023 COMPT (i)
The table Bookshop in MySQL contains the following attributes:
B_code: Integer
B_name: String
Qty: Integer
Price: Integer
The code given below updates the records from the table Bookshop in MySQL.
Statement 1 to form the cursor object.
Statement 2 to execute the query that updates the Qty to 200 of the records
whose B_code is 105 in the table.
Statement 3 to make the changes permanent in the database.
mycursor=__________ # Statement 1
qry= "update Bookshop set Qty=200 where B_code=105"
___________________ # Statement 2
___________________ # Statement 3
Ans:
import mysql.connector as mysql
def update_book():
mydb=mysql.connect(host="localhost",user="shop",passwd="Book", database
="Bstore")
mycursor=mydb.cursor() # Statement 1
qry= "update Bookshop set Qty=200 where B_code=105"
mycursor.execute(qry) # Statement 2
mydb.commit() # Statement 3
mycursor.execute("select * from bookshop")
Records=mycursor.fetchall()
count=mycursor.rowcount
print("Total number of rows = : ", count)
for row in Records:
print(row)
mydb.close()
update_book()
Python-MySQL Connectivity
CBSE-2023 COMPT (ii)
The code given below reads the records from the table Bookshop and displays all
the records:
Statement 1 to form the cursor object.
Statement 2 to write the query to display all the records from the table.
Statement 3 to read the complete result of the query into the object named
B_Details, from the table Bookshop in the database.
Ans:
Display_book()
Python-MySQL Connectivity
CBSE-2023 (i)
The code given below deletes the record from the table employee which
contains the following record structure:
E_code – Strin E_name – String Sal – Intege City - String
Ans:
Write a menu driven program to perform the following operations on a text file.
i. Write a user defined function to create a text file STORY.TXT and display
the file content.
ii. Write a user defined function in Python named showInLines() which reads
contents of a text file named STORY.TXT and displays every sentence in a
separate line. Assume that a sentence ends with a full stop (.), a question
mark (?), or an exclamation mark (!).
def showInLines():
file = open ('STORY.TXT', 'r')
lines = file.read()
print("The file is: ", lines)
for ch in lines :
if ch not in '.?!':
print(ch,sep='', end='')
else:
print(ch)
file.close()
showInLines()
def create_file():
fil=open("STORY.TXT","w+")
n=int(input("Enter number of lines : "))
for i in range(n):
data= input("Enter data to save in the text file: ")
fil.write(data)
fil.write('\n')
fil.close()
def display_file():
fil=open("STORY.TXT","r")
str = fil.read()
print(str)
fil.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File")
print("3. Displays every sentence in a separate line")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
create_file()
elif choice==2:
display_file()
elif choice==3:
showInLines()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
OUTPUT:
main()
TEXT FILE
CBSE-2024 (B)
Write a menu driven program to perform the following operations on a text file.
i. Write a user defined function to create a text file Words.txt and display
the file content.
ii. Write a function, c_words() in Python that separately counts and displays
the
number of uppercase and lowercase alphabets in a text file, Words.txt.
iii. Display the file.
iv. Exit
def c_words():
with open("Words.txt","r") as f:
Txt=f.read()
CL=CU=0
for i in Txt:
if i.islower(): # if i>="a" and i<="z":
CL+=1
elif i.isupper():# if i>="A" and i<="Z":
CU+=1
print("Number of Lowercase characters: ",CL)
print("Number of Uppercase characters: ",CU)
def create_file():
fil=open("Words.txt","w+")
n=int(input("Enter number of lines : "))
for i in range(n):
data= input("Enter data to save in the text file: ")
fil.write(data)
fil.write('\n')
fil.close()
def display_file():
fil=open("Words.txt","r")
str = fil.read()
print(str)
fil.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File")
print("3. Separately counts and displays the number of uppercase and
lowercase alphabets")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
create_file()
elif choice==2:
display_file()
elif choice==3:
c_words()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
TEXT FILE
CBSE-2023 COMPT (A)
Write a menu driven program to perform the following operations on a text file.
i. Write a user defined function to create a text file Bookname.txt and
display the file content.
ii. Write a function in Python that displays the book names having ‘Y’ or ‘y’
in their name from a text file “Bookname.txt”.
Example:
If the file “Bookname.txt” contains the names of following books:
One Hundred Years of Solitude
The Diary of a Young Girl
On the Road
Ans:
def Book_Name():
fin=open('Bookname.txt')
lines=fin.readlines()
for line in lines:
if 'y' in line or 'Y' in line: # or if 'Y' in line.upper():
print(line,end="")
fin.close()
def create_file():
fil=open("Bookname.txt","w+")
n=int(input("Enter number of lines : "))
for i in range(n):
data= input("Enter data to save in the text file: ")
fil.write(data)
fil.write('\n')
fil.close()
def display_file():
fil=open("Bookname.txt","r")
str = fil.read()
print(str)
fil.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File")
print("3. Display the books having 'y' or 'Y' in their name")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
create_file()
elif choice==2:
display_file()
elif choice==3:
Book_Name()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
TEXT FILE
CBSE-2023 COMPT (B)
Write a menu driven program to perform the following operations on a text file.
i. Write a user defined function to create a text file Input.txt and display
the file content.
ii. Write a function RevString() to read a text file “Input.txt” and prints
the words starting with ‘O’ in reverse order. The rest of the content is
displayed normally.
Example :
If content in the text file is :
UBUNTU IS AN OPEN SOURCE OPERATING SYSTEM
Output will be :
UBUNTU IS AN NEPO SOURCE GNITAREPO SYSTEM
(words ‘OPEN’ and ‘OPERATING’ are displayed in reverse order)
Ans:
def RevString():
fin=open('Input.txt')
S=fin.read()
for w in S.split():
if w.startswith('O'): # OR if w[0]=='O':
print(w[::-1],end=' ')
else:
print(w,end=' ')
print()
fin.close()
def create_file():
fil=open("Input.txt","w+")
n=int(input("Enter number of lines : "))
for i in range(n):
data= input("Enter data to save in the text file: ")
fil.write(data)
fil.write('\n')
fil.close()
def display_file():
fil=open("Input.txt","r")
str = fil.read()
print(str)
fil.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File")
print("3. Display the words starting with O in reverse order")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
create_file()
elif choice==2:
display_file()
elif choice==3:
RevString()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
TEXT FILE
CBSE-2023 (A)
Write a menu driven program to perform the following operations on a text file.
i. Write a user defined function to create a text file LINES.TXT and display
the file content.
ii. Write the definition of a Python function named LongLines() which reads
the contents of a text file named 'LINES.TXT' and displays those lines
from the file which have at least 10 words in it.
Ans:
def LongLines():
myfile=open('LINES.TXT','r')
all_lines=myfile.readlines()
for aline in all_lines:
if len(aline.split())>=10:
print(aline)
myfile.close()
#OR
def LongLines():
with open ('LINES.TXT','r') as myfile:
all_lines=myfile.readlines()
for aline in all_lines:
if len(aline.split())>=10:
print(aline)
#OR
def LongLines():
myfile=open('LINES.TXT','r')
for aline in myfile:
if len(aline.split())>=10:
print(aline)
myfile.close()
def create_file():
fil=open("LINES.TXT","w")
n=int(input("Enter number of lines : "))
for i in range(n):
data= input("Enter data to save in the text file: ")
fil.write(data)
fil.write('\n')
fil.close()
def display_file():
fil=open("LINES.TXT","r")
str = fil.read()
print(str)
fil.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File")
print("3. Display the lines from the file which have at least 10 words in
it")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
create_file()
elif choice==2:
display_file()
elif choice==3:
LongLines()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
TEXT FILE
CBSE-2023 (B)
Write a menu driven program to perform the following operations on a text file.
Example:
If the file content is as follows:
On seat2 VIP1 will sit and
On seat1 VVIP2 will be sitting
Ans:
def count_Dwords():
with open("Details.txt", 'r') as F: # ignore 'r'
S=F.read()
Wlist = S.split()
count = 0
for W in Wlist:
if W[-1].isdigit():
count+=1
print("Number of words ending with a digit are",count)
#OR
def count_Dwords():
count=0
myfile=open("Details.txt")
S=myfile.read()
Wlist=S.split()
for W in Wlist:
if W[-1] in "0123456789":
count=count+1
myfile.close()
print("Number of words ending with a digit are",count)
#OR
def count_Dwords():
myfile=open("Details.txt")
count=0
for line in myfile:
s1=line.split()
for i in s1:
if i[-1] in "0123456789":
count=count+1
print("Number of words ending with a digit are",count)
myfile.close()
def create_file():
fil=open("Details.txt","w")
n=int(input("Enter number of lines : "))
for i in range(n):
data= input("Enter data to save in the text file: ")
fil.write(data)
fil.write('\n')
fil.close()
def display_file():
fil=open("Details.txt","r")
str = fil.read()
print(str)
fil.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File")
print("3. Count the words ending with a digit")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
create_file()
elif choice==2:
display_file()
elif choice==3:
count_Dwords()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
TEXT FILE
CBSE-2021 COMPT (A)
Write a menu driven program to perform the following operations on a text file.
def ChangeGender():
f=open("BIOPIC.TXT",'r')
Text=f.read()
print(Text.replace(' he ',' she '))
f.close()
#OR
def ChangeGender():
with open ('BIOPIC.TXT', 'r') as File:
Lines = File.readlines()
for L in Lines:
Words = L.split()
for W in Words:
if W == 'he' :
W = 'she'
print(W, end = ' ')
print()
def create_file():
fil=open("BIOPIC.TXT","w")
n=int(input("Enter number of lines : "))
for i in range(n):
data= input("Enter data to save in the text file: ")
fil.write(data)
fil.write('\n')
fil.close()
def display_file():
fil=open("BIOPIC.TXT","r")
str = fil.read()
print(str)
fil.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File")
print("3. Replace the word 'he' by word 'she'")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
create_file()
elif choice==2:
display_file()
elif choice==3:
ChangeGender()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main() OUTPUT:
TEXT FILE
CBSE-2021 COMPT (B)
Write a menu driven program to perform the following operations on a text file.
Ans:
def Count_Line():
with open ('SHIVAJI.TXT', 'r') as File:
Lines = File.readlines()
print('Total number of lines :', len(Lines))
#OR
def Count_Line():
f=open("SHIVAJI.TXT",'r')
Lines=f.readlines()
print('Total number of lines :',len(Lines))
f.close()
def create_file():
fil=open("SHIVAJI.TXT","w")
n=int(input("Enter number of lines : "))
for i in range(n):
data= input("Enter data to save in the text file: ")
fil.write(data)
fil.write('\n')
fil.close()
def display_file():
fil=open("SHIVAJI.TXT","r")
str = fil.read()
print(str)
fil.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File")
print("3. Count total number of lines present in text file")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
create_file()
elif choice==2:
display_file()
elif choice==3:
Count_Line()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
BINARY FILES
CBSE-2024 (A)
Write a menu driven program to perform the following operations on a binary file
"items.dat has structure {item_id: [item_name,amount]}.
import pickle
def CreateItem():
n=int(input("Enter number of Items: "))
F1=open("items.dat",'wb')
item={}
for i in range(n):
Item_id=input("Enter Item Id: ")
Name=input("Enter Item Name: ")
Amount=int(input("Enter amount: "))
item[Item_id]=[Name,Amount]
print(item)
pickle.dump(item,F1)
F1.close()
(OR)
def Copy_new():
try:
F1=open("items.dat","rb")
F2=open("new_items.dat","wb")
D2={}
try:
while True:
D1=pickle.load(F1)
for k,v in D1.items():
if v[1]>1000:
D2[k]=v
except:
pickle.dump(D2,F2)
F1.close()
F2.close()
except:
print('File Opening Error')
(OR)
def Copy_new():
f=open("items.dat","rb")
f1=open("new_items.dat","wb")
while True:
try:
r=pickle.load(f)
for k,v in r.items():
if v[1]>1000:
pickle.dump(r, f1)
except:
break
f.close()
f1.close()
def display(File):
print("Contents in a Binary file ",File)
f=open(File,"rb")
try:
print("ID\t Name\t Amount")
while True:
R=pickle.load(f)
for k,v in R.items():
print(k,'\t',v[0],'\t',v[1])
except:
f.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File items.dat")
print("3. Copy records having amount > 1000 from items.dat to
new_items.dat.")
print("4. Display File new_items.dat")
print("5. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..5) : "))
if choice==1:
CreateItem()
elif choice==2:
display("items.dat")
elif choice==3:
Copy_new()
elif choice==4:
display("new_items.dat")
elif choice==5:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
BINARY FILES
CBSE-2024 (B)
Write a menu driven program to perform the following operations on a binary file
"EMP.DAT" has structure [Emp_Id, Name, Salary].
i. Write a user defined function CreateEmp() to input data for a record and
create a file "EMP.DAT"
ii. Write a user defined function, disp_Detail(), that would read the
contents of the file EMP.DAT and display the details of those employees
whose salary is below 25000.
iii. Display the file content.
iv. Exit
Ans:
import pickle
def CreateEmp():
n=int(input("Enter number of employees: "))
f1=open("EMP.DAT",'wb')
for i in range(n):
Emp_Id=input("Enter E. Id: ")
Name=input("Enter Name: ")
Salary=int(input("Enter Salary: "))
rec=[Emp_Id, Name, Salary]
pickle.dump(rec,f1)
f1.close()
def disp_Detail():
try:
with open("EMP.DAT","rb") as F:
try:
while True:
Data=pickle.load(F)
if Data[2]<25000:
print(Data)
except:
print("File ended")
except:
print("File Not Found!!!")
def display():
print("Contents in a Binary file ")
f=open("EMP.DAT","rb")
try:
print("ID\t Name\t Salary")
while True:
R=pickle.load(f)
print(R[0],'\t',R[1],'\t',R[2])
except:
f.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File")
print("3. Display Employees where salary is less than 25000")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
CreateEmp()
elif choice==2:
display()
elif choice==3:
disp_Detail()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
BINARY FILES
CBSE-2023
Write a menu driven program to perform the following operations on a binary file
"Cust_file.dat" has structure customer number (c_no), name (c_name), quantity
(qty), price (price) and amount (amt) of each customer [c_no,c_name, qty, price,
amt]
import pickle
def write_bin():
bin_file=open ("Cust_file.dat", "wb")
while True:
amt=None
c_no=int(input("Enter customer number: "))
c_name=input("Enter customer name: ")
qty=int(input("Enter qty: "))
price=int(input("enter price: "))
if qty<10 :
print("Quantity less than 10..Cannot SAVE")
else:
amt=price * qty
c_detail=[c_no,c_name,qty,price,amt]
pickle.dump(c_detail,bin_file)
ans=input("Do you wish to enter more records y/n")
if ans.lower()=='n':
break
bin_file.close()
def display():
print("Contents in a Binary file ")
f=open("Cust_file.dat","rb")
try:
print("no \t name \t qty \t price \t amt")
while True:
R=pickle.load(f)
print(R[0],'\t',R[1],'\t',R[2],'\t',R[3],'\t',R[4])
except:
f.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File with quantity >=10")
print("2. Display File ")
print("3. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..3) : "))
if choice==1:
write_bin()
elif choice==2:
display()
elif choice==3:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
BINARY FILES
CBSE-2021 COMPT (A)
Write a menu driven program to perform the following operations on a binary file
A binary file "PLANTS.dat" has structure (ID, NAME, PRICE).
import pickle
def WRITEREC():
f = open("PLANTS.dat","wb") # OR "ab"
data_log = []
while True:
ID = int(input("Enter ID:"))
NAME = input("Enter Name:")
PRICE = float(input("Enter Price:"))
data_log.append([ID,NAME,PRICE])
Choice=input("Do you want to add more? (Yes/No) : ")
if Choice[0].lower()=='n':
break
pickle.dump(data_log,f)
f.close()
def SHOWHIGH():
f = open("PLANTS.dat","rb")
try:
while True:
data= pickle.load(f)
for record in data:
if record[2]>500:
print("ID:",record[0])
print("Name:",record[1])
print("Price:",record[2])
print()
except:
f.close()
(OR)
import pickle
def WRITEREC() :
with open ('PLANTS.DAT', 'wb') as FW :
data_log = []
while True :
ID = input('Enter ID : ')
NAME = input('Enter NAME : ')
PRICE = float(input('Enter PRICE : '))
data_log.append([ID, NAME, PRICE])
More = input('More records (Y/N) ? ')
if More in ['n', 'N'] :break
pickle.dump(data_log,FW)
def SHOWHIGH() :
with open ('PLANTS.DAT', 'rb') as FR :
CR = pickle.load(FR)
for R in CR:
if R[2]> 500 :
print(R)
def display():
print("Contents in a Binary file ")
f=open("PLANTS.DAT","rb")
try:
print("ID \t NAME \t PRICE")
while True:
data=pickle.load(f)
for record in data:
print(record[0],'\t',record[1],'\t',record[2])
except:
f.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File ")
print("3. Display those records for which the PRICE is more than 500 ")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
WRITEREC()
elif choice==2:
display()
elif choice==3:
SHOWHIGH()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
BINARY FILES
CBSE-2021 COMPT (B)
Write a menu driven program to perform the following operations on a binary file
A binary file "PATIENTS.dat" has structure (PID, NAME, DISEASE)
import pickle
def WRITEREC():
f = open("PATIENTS.dat","wb") # OR "ab"
data_log = []
while True:
PID = int(input("Enter ID:"))
NAME = input("Enter Name:")
DISEASE = input("Enter DISEASE:")
data_log.append([PID,NAME,DISEASE])
Choice=input("Do you want to add more? (Yes/No) : ")
if Choice[0].lower()=='n':break
pickle.dump(data_log,f)
f.close()
import pickle
def countrec():
f = open("PATIENTS.dat","rb")
N=0
try:
while True:
data= pickle.load(f)
for record in data:
if record[2]=='COVID-19':
print("PID:",record[0])
print("NAME:",record[1])
print("DISEASE:",record[2])
N += 1
except:
f.close()
print('Total number of Covid-19 Patients = ', N)
(OR)
import pickle
def WRITEREC() :
with open ('PATIENTS.dat', 'wb') as FW :
data_log = []
while True :
PID = input('Enter PID : ')
NAME = input('Enter NAME : ')
DISEASE = input('Enter DISEASE : ')
data_log.append([PID, NAME, DISEASE])
More = input('More records (Y/N) ? ')
if More in ['n', 'N'] :
break
pickle.dump(data_log,FW)
def countrec():
with open ('PATIENTS.DAT', 'rb') as FR :
CR = pickle.load(FR)
N=0
for R in CR:
if (R[2]) == 'COVID-19' :
print(R)
N += 1
print('Total number of Covid-19 Patients = ', N)
def display():
print("Contents in a Binary file ")
f=open("PATIENTS.DAT","rb")
try:
print("PID \t NAME \t DISEASE")
while True:
data=pickle.load(f)
for record in data:
print(record[0],'\t',record[1],'\t',record[2])
except:
f.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File ")
print("3. Display the details of those patients who have the DISEASE as
‘COVID-19’, also display the total number of such patients ")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
WRITEREC()
elif choice==2:
display()
elif choice==3:
countrec()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
Output:
BINARY FILES
CBSE-2021 SQP (A)
Write a menu driven program to perform the following operations on a binary file
“Book.dat” has the structure {BookNo, Book_Name, Author, Price].
i. Write a user defined function CreateFile() to input data for a record and
add to “Book.dat”.
ii. Write a function CountRect() which accepts the author’s name as parameter
and count and return the number of books written by the author. Also display
the book details written by the same author.
iii. Display the file.
iv. Exit
import pickle
def CreateBook():
n=int(input("Enter number of Books: "))
f1=open("Book.dat","wb")
for i in range(n):
BookNo=input("Enter Book No: ")
Book_Name=input("Enter Book Name: ")
Author=input("Enter Author: ")
Price=int(input("Enter Price: "))
rec=[BookNo, Book_Name, Author, Price]
pickle.dump(rec,f1)
f1.close()
def CountRec(Author):
f2=open("Book.dat","rb")
print("Displaying Books by Author : ",Author)
found=0
count=0
try:
while True:
R=pickle.load(f2)
if R[2]==Author:
print("Book No: ",R[0])
print("Book Name: ", R[1])
print("Author ", R[2])
print("Price ", R[3])
count+=1
found=1
except:
f2.close()
if found==0:
print("No record found !")
else:
print("There are : ", count," books by Author ", Author)
def display():
print("Contents in a Binary file ")
f2=open("Book.dat","rb")
try:
print("BNo \t Name \t\t\t Author \t Price")
while True:
R=pickle.load(f2)
print(R[0],'\t',R[1],'\t',R[2],'\t',R[3])
except:
f2.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File")
print("3. Counting & Displaying Books by Author")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
CreateBook()
elif choice==2:
display()
#display2()
elif choice==3:
Author=input("Enter name Author name for counting books : ")
CountRec(Author)
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
BINARY FILES
CBSE-2021 SQP (B)
Write a menu driven program to perform the following operations on a binary file
"STUDENT.DAT" has structure (admission_number, Name,Percentage).
import pickle
def WRITEREC():
f = open("STUDENT.DAT","wb") # OR "ab"
St_List = []
while True:
admission_number = int(input("Enter admission number:"))
Name = input("Enter Name:")
Percentage = float(input("Enter Percentage:"))
St_List.append([admission_number,Name,Percentage])
Choice=input("Do you want to add more? (Yes/No) : ")
if Choice[0].lower()=='n':break
pickle.dump(St_List,f)
f.close()
def CountRec():
with open ('STUDENT.DAT', 'rb') as FR :
CR = pickle.load(FR)
N=0
print("AdmNo","Name","Percentage",sep='\t')
for R in CR:
if R[2] >75:
print(R[0],R[1],R[2],sep='\t')
N += 1
print('Number of student scoring above 75%= ', N)
def display():
print("Contents in a Binary file ")
f=open("STUDENT.DAT","rb")
try:
print("adm_no \t Name \t Percentage")
while True:
CR=pickle.load(f)
for R in CR:
print(R[0],'\t',R[1],'\t',R[2])
#print(R)
except:
f.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File ")
print("3. Display the details students whose percentage is above 75.
Also display number of students scoring above 75% ")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
WRITEREC()
elif choice==2:
display()
elif choice==3:
CountRec()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
CSV FILES
CBSE-2024
Write menu driven program to perfrom the following operations using UDFs:
i. Add_Device() to accept a record from the user and add it to a csv file,
Peripheral.csv.
ii. Display the file
iii. Count_Device(): To count and display number of peripheral devices whose
price is less than 1000.
iv. Exit
import csv
def Add_Device():
f=open("Peripheral.csv","w", newline='')
swriter=csv.writer(f)
swriter.writerow(['P_id','P_name','Price'])
rec=[]
while True:
P_id=int(input("Id:"))
P_name=input("Name:")
Price=int(input("Price:"))
data=[P_id, P_name, Price]
rec.append(data)
ch=input("More (Y/N)? ")
if ch in "Nn":
break
swriter.writerows(rec)
print("Data written in CSV file successfully ...")
f.close()
def Display():
f=open("Peripheral.csv","r")
print("Reading data from a CSV file..")
sreader=csv.reader(f)
for i in sreader:
print(i)
f.close()
def Count_Device():
f=open("Peripheral.csv","r")
print("Count and display number of devices whose price is less than 1000: ")
sreader=csv.reader(f)
found=0
count=0
next(sreader)
print('P_id', 'P_name', 'Price',sep='\t')
for i in sreader:
if int(i[2])<=1000:
print(i[0],i[1],i[2],sep='\t')
count+=1
found=1
if found==0:
print("Sorry.... No record found..")
else:
print("Number of devies whose price is less than 1000=",count)
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File ")
print("3. To count and display number of peripheral devices \
whose price is less than 1000 ")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
Add_Device()
elif choice==2:
Display()
elif choice==3:
Count_Device()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
CSV FILES
CBSE-2023 COMPT A
def Display_Teacher():
f=open("Teacher.csv","r")
print("Reading data from a CSV file..")
details=csv.reader(f)
for i in details:
print(i)
f.close()
def Search_Teacher():
fin=open("Teacher.csv")
details=csv.reader(fin)
for record in details:
if record[2]=="PGT":
print(record)
fin.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File ")
print("3. To display the records of all the PGT (designation) teachers.
")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
Add_Teacher()
elif choice==2:
Display_Teacher()
elif choice==3:
Search_Teacher()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
CSV FILES
CBSE SQP 2023 (A)
import csv
def ADD():
fout=open("record.csv","a",newline="\n")
wr=csv.writer(fout)
empid=int(input("Enter Employee id :: "))
name=input("Enter name :: ")
mobile=int(input("Enter mobile number :: "))
lst=[empid,name,mobile]
wr.writerow(lst)
fout.close()
def COUNTR():
fin=open("record.csv","r",newline="\n")
data=csv.reader(fin)
d=list(data)
print("Records in csv file: ")
print(d)
print("Number of records present in the CSV file: = ",len(d))
fin.close()
def Display_Records():
f1=open("record.csv","r")
print("Reading data from a CSV file..")
detail=csv.reader(f1)
for i in detail:
print(i)
f1.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File ")
print("3. To count the number of records present in the CSV file ")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
ADD()
elif choice==2:
Display_Records()
elif choice==3:
COUNTR()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
CSV FILES
CBSE SQP 2023 (B)
def Search():
fin=open("furdata.csv","r",newline='\n')
data=csv.reader(fin)
found=False
print("The Details are")
for i in data:
if int(i[2])>10000:
found=True
print(i[0],i[1],i[2])
if found==False:
print("Record not found")
fin.close()
def Display_Records():
f1=open("furdata.csv","r")
print("Reading data from a CSV file..")
detail=csv.reader(f1)
for i in detail:
print(i)
f1.close()
def main():
while True:
print("-------MAIN MENU-----")
print("1. Create File ")
print("2. Display File ")
print("3. Display the furnitures whose price is more than 10000 ")
print("4. Exit")
print("---------------------")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
Add()
elif choice==2:
Display_Records()
elif choice==3:
Search()
elif choice==4:
exit()
else:
print("Invalid Choice ! ")
main()
OUTPUT:
CSV FILES
Update Price of a given item
import csv
def create():
with open("store.csv","w",newline='') as fh:
wob= csv.writer(fh)
wob.writerow(["Productid","Productname","Price"])
ch='y'
while ch=='y':
pid=int(input('Enter the prdt id: '))
pnm=input('Enter the prdt name: ')
ppr=int(input("Enter the price: "))
wob.writerow([pid,pnm,ppr])
ch=input('Do you want to continue(y/n)?: ')
def display():
with open('store.csv','r') as rfh:
rob= csv.reader(rfh)
lines=list(rob)
for i in lines:
print('%10s'%i[0],'%15s'%i[1],'%10s'%i[2])
#print(i)
def update():
with open('store.csv','r') as rfh:
rob= csv.reader(rfh)
lines=list(rob)
upd=input('Enter the prdtid of the product, price has to be changed: ')
f=0
for i in lines:
if i[0]==upd:
pr=input('Enter the new price: ')
i[2]=pr
f=1
if f==0:
print('No such prdt is found !')
if f==1:
print('Updating...')
with open('store.csv','w',newline='') as newfh:
newob=csv.writer(newfh)
newob.writerows(lines)
print("Displaying the updated File: ")
with open('store.csv','r') as newrfh:
newrob=csv.reader(newrfh)
for i in newrob:
print('%10s'%i[0], '%15s'%i[1], '%10s'%i[2])
def main():
while True:
print("""*** MAIN MENU ***
1. Create CSV File.
2. Display CSV File.
3. Update price for a given product id.
4. Exit
""")
choice=int(input("Enter your choice (1..4) : "))
if choice==1:
create()
elif choice==2:
display()
elif choice==3:
update()
elif choice==4:
print("End of the program ! ")
exit()
else:
print("Invalid choice !")
main()
STACK Programs
CBSE-2024
Nums = [213,10025,167,254923,14,1297653,31498,386,92765]
BigNums =[]
def PushBig():
for N in Nums:
if N>=10000:
BigNums.append(N)
print("Stack elements are:")
print(BigNums)
def PopBig():
while len(BigNums)!=0:
dele=BigNums.pop()
print(dele)
else:
print("Stack Empty")
def Display():
if len(BigNums)!=0:
print("Displaying the stack elements:")
for i in range(-1,-len(BigNums)-1,-1):
print(BigNums[i])
else:
print("Stack is empty !")
while True:
print("*********MAIN MENU*********")
print("1. Push numbers which have 5 or more digits into the stack,BigNums ")
print('2. Pop Big numbers till the stack status is empty ')
print('3. Display details from stack status ')
print('4. Exit')
print("***************************")
choice=int(input("Enter your choice: 1..4:"))
if choice==1:
PushBig()
if choice==2:
PopBig()
if choice==3:
Display()
if choice==4:
print("Ending the program!")
break
OUTPUT
STACK Programs
CBSE-2023 COMPT
def Pop_element():
while len(Univ)>0:
print(Univ.pop())
else:
print("Underflow")
def Display():
if len(Univ)!=0:
print("Displaying the stack elements:")
for i in range(-1,-len(Univ)-1,-1):
print(Univ[i])
else:
print("Stack is empty !")
while True:
print("*********MAIN MENU*********")
print("1. Push objects having fees greater than 100000 to the stack into the
stack, Univ ")
print('2. Pop objects & display "Underflow" message when stack is empty ')
print('3. Display details from stack status ')
print('4. Exit')
print("***************************")
choice=int(input("Enter your choice: 1..4:"))
if choice==1:
Push_element()
if choice==2:
Pop_element()
if choice==3:
Display()
if choice==4:
print("Ending the program!")
break
OUTPUT:
STACK Programs
CBSE-2023 (A)
Customer=[["Siddarth","Delux"],["Rahul","Standard"],["Jerry","Delux"]]
Hotel=[]
H=[]
def AddCustomer():
L=[]
n=int(input("Enter number of customers to be added in List: "))
for i in range(n):
Customer_name=input("Enter Name: ")
Room_Type=input("Enter room type: ")
L=[Customer_name,Room_Type]
Customer.append(L)
print("The customers details : ")
for i in Customer:
print(i)
def Push_Cust():
for rec in Customer:
if rec[1]=="Delux":
Hotel.append(rec[0])
def Push_Cust():
for i in range(len(Customer)):
if Customer[i][1]=='Delux':
Hotel.append(Customer[i][0])
def Pop_cust():
print("Displaying the popped customer names from the stack Hotel:")
while Hotel!=[]: # or while len(Hotel)>0:
print(Hotel.pop())
else:
print("Underflow")
print()
def Display():
if len(Hotel)!=0:
print("Displaying the stack elements:")
for i in range(-1,-len(Hotel )-1,-1):
print(Hotel[i])
else:
print("Stack is empty !")
while True:
print("*********MAIN MENU*********")
#print("0. Create Customer List ")
print('1. Push Customer having Delux rooms on stack Hotel ')
print('2. Pop Customer details till the stack Hotel is empty ')
print('3. Display Customer details from stack Hotel ')
print('4. Exit')
print("***************************")
choice=int(input("Enter your choice: 1..4:"))
if choice==1:
Push_Cust()
if choice==2:
Pop_cust()
if choice==3:
Display()
if choice==4:
print("Ending the program!")
break
OUTPUT:
STACK Programs
CBSE-2023 (B)
Write a menu driven program to perform Push(), Pop() and Display() operations on
stack using dictionary.
Push(Vehicle), where, Vehicle is a dictionary containing details of vehicles -
{Car_Name: Maker}.
The functions should push the name of car manufactured by 'TATA'. (including all
the possible cases like Tata, TaTa, etc) to the stack.
For example:
If the dictionary contains the following data:
Vehicle={"Santro":"Hyundai", "Nexon":"TATA","Safari":"Tata"}
Vehicle={}
N=int(input("Enter the number of vehicles : "))
for i in range(N):
Car_Name=input("Enter Car Name: ")
Maker=input("Enter Maker name: ")
Vehicle[Car_Name]=Maker
print("The dictionary Vehicle contains:")
print(Vehicle)
Cars=[]
def Push(Vehicle):
for k in Vehicle:
if Vehicle[k].upper()=='TATA':
Cars.append(k)
print("Names of the cars manufactures by TATA added to the stack!")
C=Cars[::-1]
for i in C:
print(i)
def Pop_Vehicle():
print("The popped element from stack:")
while Cars!=[]:
print(Cars.pop())
else:
print("Stack is Empty !")
def Display():
if len(Cars)!=0:
print("The stack contains:")
for i in range(-1,-len(Cars)-1,-1):
print(Cars[i])
else:
print("Stack is empty !")
while True:
print("*********MAIN MENU*********")
print('1. Push cars manufatured by TATA on the stack Cars ')
print('2. Pop the cars till stack is empty ')
print('3. Display ')
print('4. Exit')
print("***************************")
choice=int(input("Enter your choice: 1..4:"))
if choice==1:
Push(Vehicle)
if choice==2:
Pop_Vehicle()
if choice==3:
Display()
if choice==4:
print("Ending the program!")
break
OUTPUT:
write a Menu driven program to perform operations on list (A. appending elements
and lists, B. removing elements with values and/or index, C. Reverse List)
l = []
print('empty list created')
def ADD():
global l
a = input('please enter your desired value: ')
l.append(a)
print(l)
def ADD_LIST():
global l
c = int(input('please enter the number of elements you want in the secondary
list: '))
l1 = []
for i in range(c):
a = input('enter desired value: ')
l1.append(a)
l.extend(l1)
print(l)
def POP_VALUE():
global l
c = input('please enter desired value to remove')
if c in l:
l.remove(c)
print(l)
else:
print('invalid value')
def POP():
global l
c = int(input('please enter deisred index to remove'))
if c < len(l):
l.pop(c)
print(l)
else:
print('invalid index')
def REVERSE():
global l
l.reverse()
print(l)
while True:
c = int(input('enter your choice: 1.add element to list 2.add another list
to the list 3.remove element based on value 4.remove element based on index
5.reverse list: '))
if c == 1:
ADD()
elif c == 2:
ADD_LIST()
elif c == 3:
POP_VALUE()
elif c == 4:
POP()
elif c == 5:
REVERSE()
else:
print('invalid choice')
OUTPUT:
s = str()
def create():
global s
s = input('enter desired string')
print(s)
def count():
cc = input('enter desired word to count for')
print(s.upper().count(cc.upper()))
def replace():
global s
pw = input('enter character to be replaced')
nw = input('enter desired value to replace')
if pw in s:
s = s.replace(pw,nw)
print(s)
else:
print('word not in string')
def remove():
global s
r = input('enter word to remove')
l = s.split()
s = ''
if r in l:
for i in l:
if i == r:
l.remove(i)
print(l)
s = ' '.join(l)
print(s)
while True:
c = int(input('1.chanage/create string 2.count number of deisred charcaters
3.replace chracter with desired value 4.remove certain word(s) from string
5.exit program'))
if c == 1:
create()
elif c == 2:
count()
elif c == 3:
replace()
elif c == 4:
remove()
elif c == 5:
print('exiting program')
break
else:
print('invalid choice')
OUTPUT:
Grade 11 four Programs (Menu driven programs
based on- Lists, Strings, Dictionaries, Tuples etc.)
Write a menu driven program to perform tuple operations (A. add number to a
tuple, B. remove number from the tuple C. check whether a certain number is
present in the tuple D. count number of occurrences of a number in the tuple
t = ()
def add():
global t
i = int(input('enter number to add to tuple'))
t += i,
print(t)
def remove():
global t
i = int(input('enter number to remove from tuple'))
temp = ()
for w in t:
if w == i:
continue
else:
temp += w,
t = temp
print(t)
def check():
i = int(input('enter the number for which you to check for'))
if i in t:
print(i, 'is in tuple')
else:
print('given number is not in tuple')
def count():
i = int(input('enter the number you want to count for'))
print(t.count(i))
while True:
c= int(input('1.add element to tuple \n2.remove num from tuple \n3. check for
element in tuple \n4.count number of occurences of num in tuple \n5.exit prog'))
if c == 1:
add()
elif c == 2:
remove()
elif c == 3:
check()
elif c == 4:
count()
elif c == 5:
print('exiting program')
break
else:
print('invalid choice')
OUTPUT:
Grade 11 four Programs (Menu driven programs
based on- Lists, Strings, Dictionaries, Tuples etc.)
Write a menu driven program to perform basic operations on a dictionary (A. add
record to dictionary, B. delete a record from the dictionary based on its key and
print the value of the key, C. check whether a record is present based on key and
prints the value, D. print dictionary as a table)
d = {}
def add():
global d
k = input('enter key')
v = input('enter value')
d[k] = v
print(d)
def remove():
global d
k = input('enter the key of the item you want to remove')
x =d.pop(k, 'item does not exist')
print(x)
print(d)
def check():
k = input('enter the key of the item you want to check for')
x = d.get(k, 'item does not exits')
print(x)
def print_table():
print('key value')
for i,j in d.items():
print(i,' ',j)
while True:
c = int(input('1.add to dict \n2.remove from dict \n3.check for item \
n4.print dict as table \n5.exit program'))
if c == 1:
add()
elif c == 2:
remove()
elif c == 3:
check()
elif c == 4:
print_table()
elif c == 5:
print('exiting program')
break
else:
print('invalid input')
OUTPUT: