Q1.
WAP that generates a series using a function which takes first
and the last value of the series. And then generates four terms that
are equidistant. Eg. if two numbers passed are 1 and 7 then function
returns 1 3 5 7. Display the error message if equidistant numbers
cannot be formed.
Code: -
x= int(input('enter the first number of a series: '))
y = int(input('enter last number of the series: '))
n=4
for i in range(n):
d = (y-x)//(n-1)
a=x+d
b=a+d
print(x, a, b, y)
Output: -
================X=======
X================
Q2. The function REV( ) that accept a line of text as argument and
returns the line in which each word is reversed. Display both original
and reversed line of text.
06 pg. 1
CODE: -
def Rev():
x = input('enter a line: ')
y = ''
for i in x:
y= i + y
print(x, '\n', y)
f.close()
Rev()
Output: -
================X=======
X================
Q3. WAP to accept a list of numbers and sort it in
ascending order using bubble sort.
Code: -
list = [-9, 5, 500, 2, 2821]
for i in range(len(list)):
for j in range(0, len(list) - i - 1):
if list[j] > list[j + 1]:
temp = list[j]
list[j] = list[j + 1]
list[j + 1] = temp
print('Sorted data in Ascending Order:')
print(list)
06 pg. 2
Output: -
================X=======
X================
Q4. WAP to accept a list and sort it in descending order
using insertion sort.
Code: -
lst = [15, 50, -27, -4, 10 ]
for i in range(1, len(lst)):
k = lst[i]
j=i-1
while j >= 0 and k > lst[j]:
lst[j + 1] = lst[j]
j=j-1
lst[j + 1] = k
print(lst)
Output: -
================X=======
X================
06 pg. 3
Q5. The function to find and display all the prime numbers between
2 to N, where N is passed as argument to the function
Code:-
N = int(input('enter the limiting number: '))
l=[]
for i in range(2, N):
for j in range(2, i):
if i % j == 0:
break
else:
print(i)
Output:
================X=======
X================
06 pg. 4
Q6. WA menu Driven program to perform the following
tasks for the file STUDENT.TXT:
a. Create
b. Display Whole File
c. Display Words Which Begins With Uppercase
Alphabets
d. Exit
Code: -
def W():
m = input('enter a string: ')
f = open("STUDENT.txt', 'w')
x = f.write(m)
f.close()
def F():
f = open('STUDENT.txt', 'r')
s = f.read()
print(s)
f.close()
def C():
f = open('STUDENT.txt', 'r')
06 pg. 5
s = f.read()
x = s.split()
for i in x:
if i[0].isupper() == True:
print(i)
f.close()
while True:
print('enter your choice: (1) Create: will accept the
line of text from the user and write in the file. \n (2)
Display Whole File: will display the entire content from
the file. \n (3) Display Words Which Begins With
Uppercase Alphabets: will display those words which
begins with uppercase alphabets. \n (4) Exit.')
n = int(input())
if n == 1:
W()
elif n == 2:
F()
elif n == 3:
C()
elif n == 4:
break
Output: -
06 pg. 6
================X=======
X================
Q7. WA User defined program to perform the following
functions in STUDENT.txt:
1. Remove
2. Toggle case
3. Exit
Code: -
06 pg. 7
def Rem():
f = open('STUDENT.txt', 'r')
s = f.read()
print(s)
w = input('enter the word you want to be removed: ')
d = s.replace(w, '')
print(d)
f.close()
def ConvCase():
f = open('STUDENT.txt', 'r')
s = f.read()
t=''
for i in s:
if i.isupper() == True:
t = t + i.lower()
else:
t = t + i.upper()
print(t)
f.close()
while True:
x = int(input('Enter your choice: 1) Remove a certain
word from the file. \n 2) Change the case of the text to
the opposite one. \n 3) Exit. \n'))
if x == 1:
Rem()
elif x == 2:
ConvCase()
elif x == 3:
break
Output:-
06 pg. 8
================X=======
X================
Q8. WA menu driven program to perform the following
tasks for the file DATA.txt:
1. Accept a line of text from user and write it in the
file.
2. Display the entire content from the file.
3. Transfer all uppercased characters in UPPER.txt,
and all lowercased letters in LOWER.txt.
Code: -
def Cr():
f = open('DATA.txt', 'a')
st = input('enter the text you want the file to
contain: ')
s = f.write(st)
print(s)
f.close()
def Disp():
06 pg. 9
name = input('enter the name of the file with the
extension: ')
f = open(name, 'r')
s = f.read()
print(s)
f.close()
def CaseSort():
f = open('DATA.txt', 'r')
u = open('UPPER.txt', 'a')
l = open('LOWER.txt', 'a')
d = open('DIGIT,txt', 'a')
s = f.read()
for i in s:
if i.islower():
l.write(i)
elif i.isupper():
u.write(i)
elif i.isnumeric():
d.write(i)
f.close()
u.close()
l.close()
d.close()
while True:
ch = int(input('enter your choice: 1) Enter a line of
text and enter to the file. \n 2) Display the content from
the file. \n 3) Seperate all different cased letter. \n 4)
Exit \n'))
if ch == 1:
Cr()
elif ch == 2:
Disp()
elif ch == 3:
CaseSort()
elif ch == 4:
break
06 pg.
10
Output: -
================X=======
X================
Q9. Write a menu driven program to perform the following tasks for
a binary file STUDENT.DAT containing the following structure: [rno,
name, marks, grade]
1. Create
2. Display
3. Calculate Grade
4. Search
5. Exit
CODE:-
06 pg.
11
import pickle
def display_menu():
print("Menu:")
print("1. Create")
print("2. Display")
print("3. Calculate Grade")
print("4. Search")
print("5. Exit")
def create():
roll_no = int(input("Enter your roll number: "))
name = input("Enter your name: ")
marks = int(input("Enter the marks scored out of
500: "))
student_data = {
"roll_no": roll_no,
"name": name,
"marks": marks
}
with open("Student.dat", "ab") as file:
pickle.dump(student_data, file)
print("Data saved successfully")
def display():
try:
with open("Student.dat", "rb") as file:
while True:
try:
student_data = pickle.load(file)
roll_no = student_data["roll_no"]
name = student_data["name"]
grade = student_data.get("grade", "Grade
not calculated")
06 pg.
12
print(f"{roll_no}. {name} has scored
grade {grade}")
except EOFError:
break
except FileNotFoundError:
print("No records to display. File not found.")
except pickle.UnpicklingError as e:
print(f"Error while unpickling: {e}")
def calculate_grades():
updated_data = []
with open("Student.dat", "rb") as file:
while True:
try:
student_data = pickle.load(file)
roll_no = student_data["roll_no"]
name = student_data["name"]
marks = student_data["marks"]
marks = marks // 5
if marks > 90:
grade = 'A'
elif marks > 80:
grade = 'B+'
elif marks > 70:
grade = 'B'
elif marks > 60:
grade = 'C+'
elif marks > 50:
grade = 'C'
else:
grade = 'F'
student_data["grade"] = grade
updated_data.append(student_data)
except EOFError:
06 pg.
13
break
with open("Student.dat", "wb") as file:
for student_data in updated_data:
pickle.dump(student_data, file)
print("Grades added to the file.")
def search():
search_roll_no = int(input("Enter your roll number:
"))
try:
with open("Student.dat", "rb") as file:
while True:
try:
student_data = pickle.load(file)
roll_no = student_data["roll_no"]
name = student_data["name"]
marks = student_data["marks"]
grade = student_data.get("grade", "Grade
not calculated")
if search_roll_no == roll_no:
print(f"Roll Number: {roll_no}, Name:
{name}, Marks: {marks}, Grade: {grade}")
return
except EOFError:
break
except FileNotFoundError:
print("File not found. Record not found.")
print("Record not found")
while True:
display_menu()
choice = input("Enter your choice (1-5): ")
06 pg.
14
if choice == '1':
create()
elif choice == '2':
display()
elif choice == '3':
calculate_grades()
elif choice == '4':
search()
elif choice == '5':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please enter a number
between 1 and 5.")
================X=======
X================
06 pg.
15
Q10. Write a menu driven program to perform the following tasks for
the above created binary file STUDENT.DAT.
1. Create
2. Display
3. Search
4. Modify
5. Delete
6. Exit
CODE: -
import pickle
def display_menu():
print("Menu:")
print("1. Create")
print("2. Display")
print("3. Search")
print("4. Modify")
print("5. Delete")
print("6. Exit")
def create():
roll_no = int(input("Enter your roll number: "))
name = input("Enter your name: ")
marks= int(input("Enter the marks scored out of 500:
"))
grade = calculate_grade(marks)
data = {"roll_no": roll_no, "name": name, "marks":
marks, "grade": grade}
with open("student.dat", "ab") as file:
pickle.dump(data, file)
print("Data saved successfully.")
06 pg.
16
def calculate_grade(marks):
marks = (marks//5)
if marks>90:
return 'A'
elif marks>80:
return 'B+'
elif marks>70:
return 'B'
elif marks>60:
return 'C+'
elif marks>50:
return 'C'
else:
return 'F'
def display():
with open("student.dat", "rb") as file:
while True:
try:
data = pickle.load(file)
print(f"{data['roll_no']}. {data['name']} has
scored grade {data['grade']}")
except EOFError:
break
def search():
search_roll_no = int(input("Enter your roll number:
"))
with open("student.dat", "rb") as file:
while True:
try:
data = pickle.load(file)
if search_roll_no == data['roll_no']:
print(f"Roll Number: {data['roll_no']},
Name: {data['name']}, Marks: {data['marks']}, Grade:
{data['grade']}")
return
06 pg.
17
except EOFError:
break
print("Record not found")
def modify():
search_roll_no = int(input("Enter your roll number:
"))
data_list = []
with open("student.dat", "rb") as file:
while True:
try:
data = pickle.load(file)
if search_roll_no == data['roll_no']:
data['name'] = input("Enter your name: ")
data['marks'] = int(input("Enter the marks
scored out of 500: "))
data['grade'] =
calculate_grade(data['marks'])
data_list.append(data)
except EOFError:
break
confirm = input("Do you want to modify? (Yes/No): ")
if confirm.lower() == "yes":
with open("student.dat", "wb") as file:
for data in data_list:
pickle.dump(data, file)
print("Data updated")
else:
print("Record not modified")
def delete():
search_roll_no = int(input("Enter your roll number:
"))
data_list = []
with open("student.dat", "rb") as file:
while True:
06 pg.
18
try:
data = pickle.load(file)
if search_roll_no != data['roll_no']:
data_list.append(data)
except EOFError:
break
confirm = input("Do you want to delete? (Yes/No): ")
if confirm.lower() == "yes":
with open("student.dat", "wb") as file:
for data in data_list:
pickle.dump(data, file)
print(f"Student with Roll Number {search_roll_no}
removed from the file.")
else:
print("Record not deleted")
while True:
display_menu()
choice = input("Enter your choice (1-6): ")
if choice == '1':
create()
elif choice == '2':
display()
elif choice == '3':
search()
elif choice == '4':
modify()
elif choice == '5':
delete()
elif choice == '6':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please enter a number
between 1 and 6.")
06 pg.
19
OUTPUT:-
06 pg.
20
Q11. Write a Menu Driven Program to create a csv file named
student.csv containing rollnumber, name and phone number. The
menu is as follows:
a. Read
b. Write
c. Search
d. Exit
CODE: -
import csv
def read_csv():
try:
with open('student.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
except FileNotFoundError:
06 pg.
21
print("File not found. Please use option 'b' to
create a new file.")
def write_csv():
roll_number = input("Enter Roll Number: ")
name = input("Enter Name: ")
phone_number = input("Enter Phone Number: ")
with open('student.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([roll_number, name,
phone_number])
print("Record added successfully.")
def search_csv():
search_name = input("Enter the name to search: ")
try:
with open('student.csv', 'r') as file:
reader = csv.reader(file)
found = False
for row in reader:
if row[1] == search_name:
print("Roll Number:", row[0])
print("Name:", row[1])
print("Phone Number:", row[2])
found = True
if not found:
print("No record found for", search_name)
except FileNotFoundError:
print("File not found. Please use option 'b' to
create a new file.")
while True:
print("\nMenu:")
print("a. Read")
print("b. Write")
06 pg.
22
print("c. Search")
print("d. Exit")
choice = input("Enter your choice (a/b/c/d): ").lower()
if choice == 'a':
read_csv()
elif choice == 'b':
write_csv()
elif choice == 'c':
search_csv()
elif choice == 'd':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
OUTPUT: -
06 pg.
23
Q12. Write a Menu Driven Program to perform the following tasks in
the above created csv file named student.csv. The menu is as
follows:
a. Read
b. Write
c. Modify
d. Delete
e. Exit
CODE: -
import csv
def read_csv():
try:
with open('student.csv', 'r') as file:
06 pg.
24
reader = csv.reader(file)
for row in reader:
print(row)
except FileNotFoundError:
print("File not found. Please use option 'b' to
create a new file.")
def write_csv():
roll_number = input("Enter Roll Number: ")
name = input("Enter Name: ")
phone_number = input("Enter Phone Number: ")
with open('student.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([roll_number, name,
phone_number])
print("Record added successfully.")
def modify_csv():
roll_number_to_modify = input("Enter the Roll
Number of the student to modify: ")
try:
with open('student.csv', 'r') as file:
reader = csv.reader(file)
rows = list(reader)
found = False
for i, row in enumerate(rows):
if row[0] == roll_number_to_modify:
print("Existing Record:")
print("Roll Number:", row[0])
print("Name:", row[1])
print("Phone Number:", row[2])
confirmation = input("Do you want to
modify this record? (yes/no): ").lower()
if confirmation == 'yes':
06 pg.
25
name = input("Enter new Name: ")
phone_number = input("Enter new
Phone Number: ")
rows[i] = [roll_number_to_modify, name,
phone_number]
print("Record modified successfully.")
else:
print("Modification canceled.")
found = True
break
if not found:
print("No record found for Roll Number",
roll_number_to_modify)
with open('student.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(rows)
except FileNotFoundError:
print("File not found. Please use option 'b' to
create a new file.")
def delete_csv():
roll_number_to_delete = input("Enter the Roll
Number of the student to delete: ")
try:
with open('student.csv', 'r') as file:
reader = csv.reader(file)
rows = list(reader)
found = False
for i, row in enumerate(rows):
if row[0] == roll_number_to_delete:
print("Record to delete:")
print("Roll Number:", row[0])
print("Name:", row[1])
06 pg.
26
print("Phone Number:", row[2])
confirmation = input("Do you want to
delete this record? (yes/no): ").lower()
if confirmation == 'yes':
del rows[i]
print("Record deleted successfully.")
else:
print("Deletion canceled.")
found = True
break
if not found:
print("No record found for Roll Number",
roll_number_to_delete)
with open('student.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(rows)
except FileNotFoundError:
print("File not found. Please use option 'b' to
create a new file.")
while True:
print("\nMenu:")
print("a. Read")
print("b. Write")
print("c. Modify")
print("d. Delete")
print("e. Exit")
choice = input("Enter your choice (a/b/c/d/e):
").lower()
if choice == 'a':
read_csv()
06 pg.
27
elif choice == 'b':
write_csv()
elif choice == 'c':
modify_csv()
elif choice == 'd':
delete_csv()
elif choice == 'e':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
OUTPUT: -
06 pg.
28
Q13. Write a Menu Driven Program to perform the following tasks
in the csv file named id.csv. The menu is as follows:
a. Create
b. Display All
c. Search
d. Exit
CODE: -
06 pg.
29
import csv
def is_valid_userid(userid):
return '@' in userid and (userid.endswith('.com') or
userid.endswith('.co.in'))
def is_unique_userid(userid, existing_userids):
return userid not in existing_userids
def create_csv(existing_userids):
userid = input("Enter User ID: ")
if is_valid_userid(userid) and is_unique_userid(userid,
existing_userids):
password = input("Enter Password: ")
with open('id.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([userid, password])
print("Record added successfully.")
else:
print("Invalid or non-unique User ID. Please try
again.")
def display_all():
try:
with open('id.csv', 'r') as file:
reader = csv.reader(file)
for i, row in enumerate(reader, 1):
print(f"{i}. User ID: {row[0]}, Password:
{row[1]}")
except FileNotFoundError:
print("File not found. Please use option 'a' to
create a new file.")
def search_csv():
06 pg.
30
search_userid = input("Enter the User ID to search:
")
try:
with open('id.csv', 'r') as file:
reader = csv.reader(file)
found = False
for row in reader:
if row[0] == search_userid:
print("User ID:", row[0])
print("Password:", row[1])
found = True
break
if not found:
print("No record found for User ID",
search_userid)
except FileNotFoundError:
print("File not found. Please use option 'a' to
create a new file.")
existing_userids = set()
while True:
print("\nMenu:")
print("a. Create")
print("b. Display All")
print("c. Search")
print("d. Exit")
choice = input("Enter your choice (a/b/c/d): ").lower()
if choice == 'a':
create_csv(existing_userids)
existing_userids.add(input("Enter User ID: "))
elif choice == 'b':
display_all()
elif choice == 'c':
search_csv()
06 pg.
31
elif choice == 'd':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
OUTPUT: -
06 pg.
32
Q14. Write a menu driven program to perform the following
operations in a stack.
a. PUSH
b. POP
c. TRAVERSE
d. EXIT
CODE: -
stack = []
def is_empty():
return len(stack) == 0
def push(book):
stack.append(book)
print("Book pushed successfully.")
def pop():
if not is_empty():
return stack.pop()
else:
print("Stack Underflow. Cannot POP.")
def traverse():
if not is_empty():
print("Stack Elements:")
for book in stack:
print(book)
else:
print("Stack is empty.")
06 pg.
33
while True:
print("\nMenu:")
print("a. PUSH")
print("b. POP")
print("c. TRAVERSE")
print("d. EXIT")
choice = input("Enter your choice (a/b/c/d): ").lower()
if choice == 'a':
book_no = input("Enter Book Number: ")
title = input("Enter Title: ")
author = input("Enter Author: ")
price = input("Enter Price: ")
book = [book_no, title, author, price]
push(book)
elif choice == 'b':
popped_book = pop()
if popped_book:
print("Popped Book:", popped_book)
elif choice == 'c':
traverse()
elif choice == 'd':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
OUTPUT: -
06 pg.
34
06 pg.
35
Q15. Each node of the STACK contains the following information
(i)PINCODE of a city and (ii) NAME of the city. WAP to implement
following operations:
a. PUSH
b. POP
c. DISPLAY
d. EXIT
CODE: -
stack = []
def push(arr):
for item in arr:
if str(item).endswith('3'):
stack.append(item)
def pop():
if not stack:
print("Underflow: Stack is empty")
else:
deleted_element = stack.pop()
print("Deleted element:", deleted_element)
def display():
if not stack:
print("Underflow: Stack is empty")
else:
print("Stack elements:")
for item in stack:
print(item)
while True:
06 pg.
36
print("\nSTACK OPERATIONS:")
print("a. PUSH")
print("b. POP")
print("c. DISPLAY")
print("d. EXIT")
choice = input("Enter your choice (a/b/c/d): ")
if choice == 'a':
arr = input("Enter elements separated by space to push into the
stack: ").split()
push(arr)
elif choice == 'b':
pop()
elif choice == 'c':
display()
elif choice == 'd':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option (a/b/c/d).")
06 pg.
37
OUTPUT: -
06 pg.
38
Q16. Consider the following tables GAMES and PLAYER and answer
parts of this question:
(i) To display the name of all GAMES with their GCodes
(ii) To display details of those GAMES which are having PrizeMoney
more than 7000.
(iii) To display the content of the GAMES table in ascending order of
Schedule Date.
(iv) To display sum of PrizeMoney for each Type of GAMES.
06 pg.
39
Answer:-
(i) SELECT GCode, GameName from games;
(ii) SELECT * from games where PrizeMoney>7000;
(iii) SELECT * from games order by ScheduleDate;
(iv) SELECT SUM(PrizeMoney) from games group by Type;
06 pg.
40
Q17. Consider the following tables Stationary and Consumer. Write
SQL commands for the statement (i) to (iv):
(i) To display the details of those consumers whose Address is Delhi.
(ii) To display the details of Stationary whose Price is in the range of 8
to 15. (Both Value included)
(iii) To display the ConsumerName, Address from Table Consumer,
and Company and Price from table Stationary, with their
corresponding matching S_ID.
(iv) To increase the Price of all stationary by 2.
Answer:-
(i) SELECT ConsumerName from consumer where
Address='Delhi';
06 pg.
41
(ii) SELECT * from stationary where Price BETWEEN 8 and 15;
(iii) SELECT ConsumerName, Address, Company, Price from
consumer, stationary where consumer.S_ID=stationary.S_ID;
(iv) UPDATE stationary set Price=Price+2;
06 pg.
42
Q18. Consider the following table RESORT and OWNEDBY and
answer the following questions:
(i) To display the RCODE and PLACE of all ‘2 Star’ resorts in the
alphabetical order of the place from table RESORT.
(ii) To display the maximum & minimum rent for each type of resort
from table RESORT.
(iii) To display the details of all resorts which are started after 31-
Dec-04 from table RESORT.
(iv) To display the owner of all ‘5 Star’ resorts from tables RESORT
and OWNEDBY.
06 pg.
43
ANSWERS:-
(i) SELECT RCODE, PLACE from resort where TYPE=’2 Star’ order
by PLACE;
(ii) SELECT TYPE, MAX(RENT), MIN(RENT) from resort group by
TYPE;
(iii) SELECT * from resort where STARTDATE>'2004- 12-31';
(iv) SELECT OWNER from resort, ownedby where
ownedby.PLACE=resort.PLACE and TYPE='5 Star';
06 pg.
44