0% found this document useful (0 votes)
137 views75 pages

Shravan Nagendran Grade 12 Practical File Computer Science

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

Shravan Nagendran Grade 12 Practical File Computer Science

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

COMPUTER SCIENCE

PRACTICAL RECORD FILE

SUBMITTED BY:

NAME: SHRAVAN NAGENDRAN.


CLASS: 12-B.
Academic Year: 2024-2025
CERTIFICATE

CBSE Board Roll No:………………..

This is to Certify that, Master …..SHRAVAN NAGENDRAN…….


of Grade 12, Sec. B has carried out the Record File Programs in
Computer Science as prescribed by the Central Board of
Secondary Education, New Delhi during the Academic Year,
2024 – 2025.

Teacher-In Charge : Ms. Manimekalai Balaguru

Date :

Internal Examiner External Examiner


INDEX
EXP. TITLE OF PROGRAM Sign
NO.
MYSQL Queries Based on 2 Tables
1 CBSE 2024: Tables Admin and Transport
2 CBSE 2023 COMPT: Tables COMPANY and CUSTOMER
3 CBSE 2023: Relations COMPUTER and SALES
4 CBSE 2022: tables PASSENGER and FLIGHT
MYSQL-PYHTON CONNECTIVITY Programs
5 CBSE-2024 (i)
6 CBSE-2024 (ii)
7 CBSE-2023 COMPT (i)
8 CBSE-2023 COMPT (ii)
9 CBSE-2023 (i)
10 MYSQL-PYHTON CONNECTIVITY – CBSE-2023 (ii)
TEXT FILE programs
11 CBSE-2024 (A)- Display every sentence in a separate line.
CBSE-2024 (B)- Display number of uppercase and
lowercase alphabets
12 CBSE-2023 – COMPT(A)- Display the book names having ‘Y’
or ‘y’ in their name.
CBSE-2023 – COMPT(B)- Print the words starting with ‘O’
in reverse order.
13 CBSE-2023 (A)- Display those lines from the file which
have at least 10 words in it.
CBSE-2023 (B)- Count the words ending with a digit.
14 CBSE-2021 - COMPT(A)- displays the content of the file
with every occurrence of the word 'he' replaced by 'she'.
CBSE-2021 - COMPT(B)- Count total number of lines
present in text file.
BINARY FILE Programs
15 CBSE-2024 (A)- Copies all the records whose amount is
greater than 1000 to new file
CBSE-2024 (B)- Display the details of employees having
salary below 25000
16 CBSE 2023- Store only those items whose quantity is >10
17 CBSE-2021 COMPT (A): Displays those records for which
the PRICE is more than 500
CBSE-2021 COMPT (B): display the details of those
patients who have the DISEASE as ‘COVID-19’, also display
the total number of such patients
18 CBSE-2021 SQP (A): Print number of books by the given
Author
CBSE-2021 SQP (B): Display the details of those students
whose percentage is above 75
SQL Queries based on Two Table
CBSE-2024

Consider the tables Admin and Transport given below:


Table: Admin
S_id S_Name Address S_type
S001 Sandhya Rohini Day Boarder
S002 Vedanshi Rohtak Day Scholar
S003 Vibhu Raj Nagar NULL
S004 Atharva Rampur Day Boarder
Table: Transport
S_id Sub_no Stop_name
S002 TSS10 Sarai Kale Khan
S004 TSS12 Sainik Vihar
S005 TSS10 Kamla Nagar

Write SQL queries for the following:


(i) Display the student name and their stop name from the tables Admin and
Transport.
(ii) Display the number of students whose S_type is not known.
(iii) Display all details of the students whose name starts with 'V'.
(iv) Display student id and address in alphabetical order of student name,
from the table Admin.
Ans:
(i) SELECT S_name, Stop_name
FROM Admin A, Transport T
WHERE A.S_id=T.S_id;

(OR)

SELECT S_name, Stop_name


FROM Admin, Transport
WHERE Admin.S_id=Transport.S_id;

(ii) SELECT COUNT(*) FROM Admin WHERE S_type IS NULL;

(iii) SELECT * FROM Admin WHERE S_name LIKE 'V%';

(iv) SELECT S_id, Address


FROM Admin
ORDER BY S_name ASC;

(OR)

SELECT S_id, Address


FROM Admin
ORDER BY S_name;
SQL Queries based on Two Table
CBSE-2023 COMPT

Consider the tables COMPANY and CUSTOMER given below:


Table: COMPANY
CID C-NAME CITY PRODUCTNAME
111 SONY DELHI TV
222 NOKIA MUMBAI MOBILE
333 ONIDA DELHI TV
444 SONY MUMBAI MOBILE
555 BLACKBERRY CHENNAI MOBILE
666 DELL DELHI LAPTOP

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

Write SQL queries for the following:


(i) Display product name, and number of products where the number of
products is more than 2.
(ii) Display Name, Price and product name from tables Company and customer
where C_name is SONY
(iii) Display unique City names from table Company.
(iv) Display all details from table Company where C_Name has ‘ON’ in it.

Ans:

(i) SELECT PRODUCTNAME, COUNT(*) FROM COMPANY


GROUP BY PRODUCTNAME
HAVING COUNT(*)> 2;

(ii) SELECT NAME, PRICE, PRODUCTNAME


FROM COMPANY C, CUSTOMER CT
WHERE C.CID = CU.CID AND C_NAME = 'SONY';

(iii) SELECT DISTINCT CITY FROM COMPANY;

(iv) SELECT * FROM COMPANY WHERE C_NAME LIKE '%ON%';


SQL Queries based on Two Table
CBSE 2023

Consider the tables COMPUTER and SALES given below:


Table: COMPUTER
PROD_ID PROD_NAME PRICE COMPANY TYPE
P001 MOUSE 200 LOGITECH INPUT
P002 LASER PRINTER 4000 CANON OUTPUT
P003 KEYBOARD 500 LOGITECH INPUT
P004 JOYSTICK 1000 IBALL INPUT
P005 SPEAKER 1200 CREATIVE OUTPUT
P006 DESKJET PRINTER 4300 CANON OUTPUT

Table: SALES
PROD_ID QTY_SOLD QUARTER
P002 4 1
P003 2 2
P001 3 2
P004 2 1

Write SQL queries for the following:


(i) Display lowest and highest price form table Computer.
(ii) Display Company and number of companies where number of companies is
more than one.
(iii) Display product name, quantity sold for all input devise from tables
Computer and Sales.
(iv) Display Product name, Company name and Quarter from tables Computer
and Sales.
Ans:
(i) SELECT MIN(PRICE), MAX(PRICE) FROM COMPUTER;

(ii) SELECT COMPANY, COUNT(*)


FROM COMPUTER GROUP BY COMPANY
HAVING COUNT(COMPANY)>1;

(iii) SELECT PROD_NAME, QTY_SOLD


FROM COMPUTER C, SALES S
WHERE C.PROD_ID=S.PROD_ID AND TYPE = 'INPUT';

(iv) SELECT PROD_NAME, COMPANY, QUARTER


FROM COMPUTER C, SALES S
WHERE C.PROD_ID=S.PROD_ID;
SQL Queries based on Two Tables
CBSE-2022

Consider the tables PASSENGER and FLIGHT given below:


Table: PASSENGER
PNO NAME GENDER FNO
1001 Suresh MALE F101
1002 Anita FEMALE F104
1003 Harjas MALE F102
1004 Nita FEMALE F103

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

Write SQL queries for the following:


(i) Write a query to change the fare to 6000 of the flight whose FNO is
F104.
(ii) Write a query to display the total number of MALE and FEMALE
PASSENGERS.
(iii) Write a query to display the NAME, corresponding FARE and F_DATE of
all PASSENGERS who have a flight to START from DELHI.
(iv) Write a query to delete the records of the flights which end at
MUMBAI.
Ans:

(i) UPDATE FLIGHT SET FARE=6000 WHERE FNO='F104';

(ii) SELECT GENDER, COUNT(*) "TOTAL NUMBER" FROM PASSENGER GROUP BY GENDER;

(iii) SELECT NAME, FARE , F_DATE FROM FLIGHT F, PASSENGER P WHERE


F.FNO=P.FNO AND START='DELHI';

(iv) DELETE FROM FLIGHT WHERE END='MUMBAI';


Python-MySQL Connectivity
CBSE-2024 (i)
Sunil wants to write a program in Python to update the quantity to 20 of the
records whose item code is 111 in the table named shop in MySQL database named
Keeper.
Tho table shop in MySQL contains the following attributes:
• Item_code: Item code (Integer)
• Item_name: Name of item (String)
• Qty: Quantity of item (Integer)
• Price: Price of item (Integer)
Consider the following to establish connectivity between Python and MySQL:
• Username: admin
• Password: Shopping
• Host: localhost
Program:
import mysql.connector
con=mysql.connector.connect(host="localhost",user="admin", passwd='shopping',
database='keeper')
cur=con.cursor()
query='update shop set qty= 20 where Item_code=111'
cur.execute(query)
con.commit()

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

Note the following to establish connectivity between Python and MySQL:


Username: shop
Password: Book
Database: Bstore.

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.

import mysql.connector as mysql


def update_book():
mydb=mysql.connect(host="localhost",
user="shop",passwd="Book",database="Bstore")

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 table Bookshop in MySQL contains the following attributes:


B_code: Integer
B_name: String
Qty: Integer
Price: Integer

Note the following to establish connectivity between Python and MySQL :


Usernname: shop
Password: Book
The table exists in a MySQL database named Bstore.

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.

import mysql.connector as mysql


def Display_book():
mydb=mysql.connect(host="localhost",user="shop",
passwd="Book",database="Bstore")
mycursor=___________ # Statement 1
mycursor.execute("_________") # Statement 2
B_Details=__________ # Statement 3
for i in B_Details:
print(i)

Ans:

import mysql.connector as mysql


def Display_book():
mydb=mysql.connect(host=’localholst’, user=’shop’,
passwd=’Book’,database=’Bstore)
mycursor=mydb.cursor() # Statement 1
mycursor.execute("select * from bookshop") # Statement 2
B_Details=mycursor.fetchall() # Statement 3
for i in B_Details:
print(i)

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

Note the following to establish connectivity between Python and MySQL:


· Username and Password is root
· The table exists in a MySQL database named emp.

Write the following statements to complete the code :


Statement 1 – to import the desired library.
Statement 2 – to execute the command that deletes the record with E_code as
'E101'.
Statement 3 – to delete the record permanently from the database.

import __________ as mysql # Statement 1


def delete() :
mydb=mysql.connect(host="localhost",user="root",passwd="root",database="emp")
mycursor=mydb.cursor()
_________________ # Statement 2
_________________ # Statement 3
print ("Record deleted")
mycursor.execute("select * from employee")
Records=mycursor.fetchall()
count=mycursor.rowcount
print("Total number of rows = : ", count)
for row in Records:
print(row)
mydb.close()
delete()

Ans:

import mysql.connector as mysql # Statement 1


def delete():
mydb=mysql.connect(host="localhost",user="root",passwd="root",database="emp")
mycursor=mydb.cursor()
mycursor.execute("DELETE FROM employee WHERE E_code='E101'") # Statement 2
mydb.commit() # Statement 3
print ("Record deleted")
mycursor.execute("select * from employee")
Records=mycursor.fetchall()
count=mycursor.rowcount
print("Total number of rows = : ", count)
for row in Records:
print(row)
mydb.close()
delete()
TEXT FILE
CBSE-2024 (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 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 (!).

For example, if the content of file STORY.TXT is as follows:


Our parents told us that we must eat vegetables to be
healthy. And it turns out, our parents were right! So, what else
did our parents tell?

Then the function should display the file’s content as follows:

Our parents told us that we must eat vegetables to be healthy.


And it turns out, our parents were right!
So, what else did our parents tell?

iii. Display the file.


iv. Exit

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

After execution, the output will be:


One Hundred Years of Solitude
The Diary of a Young Girl

iii. Display the file.


iv. Exit

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)

iii. Display the file.


iv. Exit

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.

For example, if the content of 'LINES.TXT' is as follows:


Once upon a time, there was a woodcutter.
He lived in a little house in a beautiful, green wood.
One day, he was merrily chopping some wood.
He saw a little girl skipping through the woods, whistling happily.
The girl was followed by a big gray wolf.

Then the function should display output as :


He lived in a little house in a beautiful, green wood.
He saw a little girl skipping through the woods, whistling happily.
iii. Display the file.
iv. Exit

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.

i. Write a user defined function to create a text file Details.txt and


display the file content.
ii. Write a function count_Dwords() in Python to count the words ending with
a digit in a text file "Details.txt".

Example:
If the file content is as follows:
On seat2 VIP1 will sit and
On seat1 VVIP2 will be sitting

Output will be:


Number of words ending with a digit are 4

iii. Display the file.


iv. Exit

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.

i. Write a user defined function to create a text file BIOPIC.TXT and


display the file content.
ii. Write the definition of a function ChangeGender() in Python , which reads
the contents of a text file "BIOPIC.TXT" and displays the content of the
file with every occurrence of the word 'he' replaced by 'she'.
For example, if the content of the file "BIOPIC.TXT" is as follows:
Last time he went to Agra,
there was too much crowd, which he did not like.
So this time he decided to visit some hill station.
The function should read the file content and display the output as:
Last time she went to Agra,
there was too much crowd, which she did not like.
So this time she decided to visit some hill station.

iii. Display the file.


iv. Exit
Ans:

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.

i. Write a user defined function to create a text file SHIVAJI.TXT and


display the file content.
ii. Write the definition of a function Count_Line() in Python, which should
read each line of a text file "SHIVAJI.TXT" and count total number of
lines present in text file.

For example, if the content of the file "SHIVAJI.TXT" is as follows:


Shivaji was born in the family of Bhonsle.
He was devoted to his mother Jijabai.
India at that time was under Muslim rule.
The function should read the file content and display the output as:
Total number of lines: 3

iii. Display the file.


iv. Exit

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]}.

i. Write a user defined function to add more records of employees in the


existing file "items.dat"
ii. Display file items.dat
iii. Write a function, Copy_new(), that copies all records whose amount is
greater than 1000 from items.dat to new_items.dat.
iv. Display the file content.
v. Exit

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]

i. Write a user defined function named write_bin() to create a binary file


called Cust_file.dat containing customer information – customer number
(c_no), name (c_name), quantity (qty), price (price) and amount (amt) of
each customer.
The function accepts customer number, name, quantity and price.
Thereafter, it displays the message ‘Quantity less than 10 ….. Cannot
SAVE’, if quantity entered is less than 10. Otherwise the function
calculates amount as price * quantity and then writes the record in the
form of a list into the binary file.
ii. Display file
iii. Exit

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

i. Write the definition of a function WRITEREC() in Python, to input data


for records from the user and write them to the file PLANTS.dat.
ii. Display the content of the file
iii. Write the definition of a function SHOWHIGH() in Python, which reads the
records of PLANTS.dat and displays those records for which the PRICE is
more than 500.
iv. Exit

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)

i. Write the definition of a function WRITEREC() in Python, to input data


for records from the user and write them to the file "PATIENTS.dat".
ii. Display file
iii. Write the definition of a function countrec() in Python that would read
contents of the file "PATIENTS.dat" and display the details of those
patients who have the DISEASE as ‘COVID-19’. The function should also
display the total number of such patients whose DISEASE is 'COVID-19'.
iv. Exit

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

i. Write the definition of a function WRITEREC() in Python, to input data


for records from the user and write them to the file "STUDENT.DAT".
ii. Display the records from the file.
iii. Write a function countrec() in Python that would read contents of the
file "STUDENT.DAT" and display the details of those students whose
percentage is above 75. Also display number of students scoring above 75%
iv. Exit

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

Sangeeta is a Python programmer working in a computer hardware company. She has


to maintain the records of the peripheral devices. She created a csv file named
Peripheral.csv, to store the details. The structure of Peripheral.csv is:
[P_id,P_name,Price], where

P_id is Peripheral device ID (integer)


P_name is Peripheral device name (String)
Price is Peripheral device price (integer)

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

Write a menu-driven program in Python using UDFs to perform the following


operations:
i. Add_Teacher() : It accepts the values from the user and inserts record of a
teacher to a csv file 'Teacher.csv'. Each record consists of a list with
field elements as T_id,Tname and desig to store teacher ID, teacher name and
designation respectively.
ii. Display_Teacher(): To display all records.
iii. Search_Teacher() : To display the records of all the PGT (designation)
teachers.
iv. Exit
import csv
def Add_Teacher():
fh=open("Teacher.csv","a",newline="\n")
T_id=int(input("Enter Teacher id: "))
Tname=input("Enter Teacher name: ")
desig=input("Enter Designation: [PGT/TGT] : ")
rec=[T_id,Tname,desig]
csvw=csv.writer(fh)
csvw.writerow(rec)
fh.close()

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)

Write a menu-driven program in Python uisng UDFs to perform the following


operations:
i. ADD() – To accept and add data of an employee to a CSV file ‘record.csv’.
Each record consists of a list with field elements as empid, name and mobile
to store employee id, employee name and employee salary respectively.
ii. Display_Records()- To display all records.
iii. COUNTR() – To count the number of records present in the CSV file named
‘record.csv’.
iv. Exit

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)

Write a menu-driven program in Python uisng UDFs to perform the following


operations:

i. Add() – To accept and add data of an employee to a CSV file 'furdata.csv’.


each record consists of a list with field elements as fid, fname and fprice
to store furniture id, furniture name and furniture price respectively.
ii. Display_Records()- To display all records.
iii. Search()- To display the records of the furniture whose price is more than
10000.
iv. Exit
import csv
def Add():
fout=open("furdata.csv","a",newline='\n')
wr=csv.writer(fout)
fid=int(input("Enter Furniture Id :: "))
fname=input("Enter Furniture name :: ")
fprice=int(input("Enter price :: "))
FD=[fid,fname,fprice]
wr.writerow(FD)
fout.close()

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

Write a menu driven program using UDFs to:


i. Create a csv file store.csv to store pid- product id, pname- product name,
ppr- product price.
ii. Display csv file.
iii. Update csv file.
iv. Exit

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

Consider a list named Nums which contains random integers.


Write a menu-driven program using UDFs to perform following specified operations
on a stack named BigNums.
i. PushBig() : It checks every number from the list Nums and pushes all such
numbers which have 5 or more digits into the stack, BigNums
ii. PopBig() • It pops the numbers from the stack, BigNums and display them. The
function should also display "Stack Empty" when there are no more numbers
left in the stack.
iii. Display details from stack status.
iv. Exit

For example: If the list Nums contains the following data :


Nums = [213,10025,167,254923,14,1297653,31498,386,92765]

Then on execution of PushBig(), the stack BigNumg should store:


[10025, 254923, 1297653, 31498, 92765]

And on execution of PopBig(), the following output should be displayed:


92765
31498
1297653
254923
10025
Stack Empty

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

A list contains following record of course details for a University :


[Course_name, Fees, Duration]

Write a menu-driven program using UDFs to perform following specified operations


on a stack named 'Univ'.
i. Push_element() - To push an object containing the Course_name, Fees and
Duration of a course, which has fees greater than 100000 to the stack.
ii. Pop_element() - To pop the object from the stack and display it. Also,
display "Underflow: when there is no element in the stack.
iii. Display details from stack status.
iv. Exit
For example :
If the lists of courses details are :
["MCA", 200000, 3]
["MBA", 500000, 2]
["BA", 100000, 3]

The stack should contain


["MBA", 500000, 2]
["MCA", 200000, 3]

Course= [["MCA", 200000, 3],["MBA", 500000, 2],["BA", 100000, 3]]


Univ =[]
def Push_element():
for Rec in Course:
if Rec[1]>100000:
Univ.append(Rec)
print("Stack elements are:")
print(Univ)

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)

A list contains records of customer [Customer_name, Room_Type]. Write the


following user defined functions to perform given operations on the stack name
Hotel
i. Push_Cust()- To push customer's names of those customers who are staying
in Delux Room Type
ii. Pop_cust()- To Pop the names of customers from the stack and display
them. Also, display 'Underflow' when there are no customers in the stack.
iii. Display Customer details from stack Hotel.
iv. Exit
Fox example:
If the lists with customer detail are as follows:
["Siddarth","Delux"]
["Rahul","Standard"]
["Jerry","Delux"]

The stack should contain:


Jerry
Siddharth

The Output should be:


Jerry
Siddharth
Underflow

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

print("Displaying Stack Hotel details: ")


H=Hotel[::-1]
for i in H:
print(i)

def Push_Cust():
for i in range(len(Customer)):
if Customer[i][1]=='Delux':
Hotel.append(Customer[i][0])

print("Displaying Stack Hotel details: ")


H=Hotel[::-1]
for i in H:
print(i)

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

After Push() operation the stack should contain:


Safari
Nexon

After Pop() operations:


The popped element from stack:
Safari
Nexon
Stack is Empty

Display function should display:


The stack contains:
Safari
Nexon

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:

Grade 11 four Programs (Menu driven programs


based on- Lists, Strings, Dictionaries, Tuples etc.)

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:

Grade 11 four Programs (Menu driven programs


based on- Lists, Strings, Dictionaries, Tuples etc.)
write a Menu Driven program to perform operations on String (A. making or
changing string, B.count number of specified value in string, c. replace
character with certain value, D. remove a certain word from the string. E. Exit
program)

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:

You might also like