Cs Practical
Cs Practical
PRACTICAL FILE
NAME: Nagmani
CLASS: XII-A
ROLL NO: 16
INDEX
S. Teachers
NO CHAPTER Questions Page
. sign
Working with
1 Q1 - Q5 Pg.4 - Pg.8
Functions
Output
2. 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.
Sol:- Code
def rev(line):
words = line.split()
reversed_line = ' '.join(w[::-1] for w in words)
return reversed_line
Output
3. WAP to accept the list and sort it in ascending order
using bubble sort.
Sol:- Code
def bubble_sort(lst):
n = len(lst)
for i in range(n):
for j in range(n - i - 1):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
Output
4. WAP to accept the list and sort it in descending order
using insertion sort
Sol:- Code
def insertion_sort(lst):
n = len(lst)
for i in range(1, n):
key = lst[i]
j=i-1
while j >= 0 and lst[j] < key:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = key
Output
5. The function to find and display all the prime
numbers between 2 to N, where N is passed as
argument to the function.
Sol:- Code
def find_primes(n):
primes = []
for num in range(2, n + 1):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
primes.append(num)
return primes
Output
Data Files
6. 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
# Create: will accept the line of text from the user and write in the
file.
# Display Whole File: will display the entire content from the file.
# Display Words Which Begins With Uppercase Alphabets: will display
those words which begins with uppercase alphabets.
Sol:- Code
def create_file():
text = input("Enter a line of text: ")
with open("STUDENT.TXT", "w") as file:
file.write(text)
print("File created successfully.")
def display_file():
with open("STUDENT.TXT", "r") as file:
content = file.read()
print("File Content:\n", content)
def display_uppercase_words():
with open("STUDENT.TXT", "r") as file:
content = file.read()
words = content.split()
uppercase_words = [word for word in words if word[0].isupper()]
print("Words beginning with uppercase alphabets:\n", uppercase_words)
while True:
print("\nMenu:")
print("a. Create")
print("b. Display Whole File")
print("c. Display Words Which Begins With Uppercase Alphabets")
print("d. Exit")
choice = input("Enter your choice (a, b, c, or d): ")
if choice == 'a':
create_file()
elif choice == 'b':
display_file()
elif choice == 'c':
display_uppercase_words()
elif choice == 'd':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
Output
7. WA menu Driven program to perform the following
tasks for the above created file STUDENT.TXT:
a. Remove
b. Convert Case
c. Exit
# Remove Word: will delete the word entered by the
user from the file.
# Convert Case: will convert each character to its
opposite case
Sol:- Code
def convert_case(file):
with open(file, 'r+') as f:
content = f.read()
f.seek(0)
f.write(content.swapcase())
f.truncate()
def display_menu():
print("Menu:")
print("a. Remove Word")
print("b. Convert Case")
print("c. Exit")
filename = "STUDENT.TXT"
while True:
display_menu()
choice = input("Enter your choice (a, b, or c): ")
if choice == 'a':
word = input("Enter the word to remove: ")
remove_word(filename, word)
print("Word removed successfully.")
else:
print("Invalid choice. Please try again.")
Output
8. WA menu Driven program to perform the following
tasks for the file DATA.TXT:
a. Create
b. Display all
c. Shift Data
d. Exit
# Create: will accept the line of text from the user and
write in the file.
# Display all: will display the entire content from the
file. The name of the file is entered as an argument to
the function.
# Shift Data: will transfer all the uppercase characters
in UPPER.TXT, all lowercase characters in LOWER.TXT
and all digits in DIGIT.TXT
Sol:- Code
def create_file():
txt = input("Enter a line of text: ")
with open("DATA.TXT", "w") as f:
f.write(txt)
print("File created successfully.")
def display_all(file):
with open(file, "r") as f:
content = f.read()
print("File Content:\n", content)
def shift_data():
with open("DATA.TXT", "r") as f:
content = f.read()
upper = ''
lower = ''
digits = ''
for char in content:
if char.isupper():
upper += char
elif char.islower():
lower += char
elif char.isdigit():
digits += char
while True:
print("\nMenu:")
print("a. Create")
print("b. Display all")
print("c. Shift Data")
print("d. Exit")
if choice == 'a':
create_file()
elif choice == 'b':
display_all("DATA.TXT")
elif choice == 'c':
shift_data()
elif choice == 'd':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
Output
9. 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
#Create: must ask the user to enter roll number, name
and marks(out of 500) for the student and write into
the file.
#Display: must display each record on separate line in
the following format:
<rno>, <names>has scored grade <grade>
If grade is not calculated display () function must
display the following message:
“Grade not calculated. No record to display”
def c(self):
r = int(input("Enter roll number: "))
n = input("Enter name: ")
m = int(input("Enter marks (out of 500): "))
with open(self.f, "a") as f:
f.write(f"{r},{n},{m}\n")
print("Record created successfully.")
def d(self):
with open(self.f, "r") as f:
c = f.readlines()
if c:
for l in c:
r, n, m = l.strip().split(',')
print(f"{r} , {n} has scored grade {self.g(int(m))}")
else:
print("Grade not calculated. No record to
display.")
f = "S.DAT"
s = S(f)
while True:
print("\nMenu:")
print("1. Create")
print("2. Display")
print("3. Calculate Grade")
print("4. Search")
print("5. Exit")
c = int(input("Enter your choice (1-5): "))
if c == 1:
s.c()
elif c == 2:
s.d()
elif c == 3:
m = int(input("Enter marks: "))
print(f"Grade: {s.g(m)}")
elif c == 4:
r = int(input("Enter roll number: "))
s.s(r)
elif c == 5:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
Output
10. 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
#Create: must ask the user to enter roll number, name
and marks(out of 500) for the student and write into
the file.
#Display: must display each record on separate line in
the following format:
<rno>, <names>has scored grade <grade>
If grade is not calculated display () function must
display the following message:
“Grade not calculated. No record to display”
#Modify: must ask roll number of the student and
modify the remaining details after taking confirmation
from the user.
#Delete: must ask roll number of the student and
delete the record after taking confirmation from the
user.
Sol:- Code
'''class StudentFile:
def __init__(self, filename):
self.filename = filename
def create(self):
rno = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = int(input("Enter marks (out of 500): "))
with open(self.filename, "a") as file:
file.write(f"{rno},{name},{marks}\n")
print("Record created successfully.")
def display(self):
with open(self.filename, "r") as file:
content = file.readlines()
if content:
for line in content:
rno, name, marks = line.strip().split(',')
print(f"{rno} , {name} has scored grade
{self.calculate_grade(int(marks))}")
else:
print("Grade not calculated. No record to
display.")
filename = "STUDENT.DAT"
sf = StudentFile(filename)
while True:
print("\nMenu:")
print("1. Create")
print("2. Display")
print("3. Calculate Grade")
print("4. Search")
print("5. Exit")
choice = int(input("Enter your choice (1-5): "))
if choice == 1:
sf.create()
elif choice == 2:
sf.display()
elif choice == 3:
marks = int(input("Enter marks: "))
print(f"Grade: {sf.calculate_grade(marks)}")
elif choice == 4:
rno = int(input("Enter roll number: "))
sf.search(rno)
elif choice == 5:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")'''
class StudentFile:
def __init__(self, filename):
self.filename = filename
def create(self):
rno = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = int(input("Enter marks (out of 500): "))
with open(self.filename, "a") as file:
file.write(f"{rno},{name},{marks}\n")
print("Record created successfully.")
def display(self):
with open(self.filename, "r") as file:
content = file.readlines()
if content:
for line in content:
rno, name, marks = line.strip().split(',')
print(f"{rno} , {name} has scored grade
{self.calculate_grade(int(marks))}")
else:
print("Grade not calculated. No record to display.")
def modify(self):
rno = int(input("Enter roll number to modify: "))
found = False
with open(self.filename, "r") as file:
content = file.readlines()
for i, line in enumerate(content):
s_rno, name, marks = line.strip().split(',')
if int(s_rno) == rno:
found = True
new_name = input("Enter new name: ")
new_marks = int(input("Enter new marks (out of 500): "))
content[i] = f"{rno},{new_name},{new_marks}\n"
with open(self.filename, "w") as file:
file.writelines(content)
print("Record modified successfully.")
break
if not found:
print("Record Not Found")
def delete(self):
rno = int(input("Enter roll number to delete: "))
found = False
with open(self.filename, "r") as file:
content = file.readlines()
for i, line in enumerate(content):
s_rno, name, marks = line.strip().split(',')
if int(s_rno) == rno:
found = True
confirmation = input("Are you sure you want to delete this record? (yes/no): ")
if confirmation.lower() == "yes":
del content[i]
with open(self.filename, "w") as file:
file.writelines(content)
print("Record deleted successfully.")
else:
print("Deletion cancelled.")
break
if not found:
print("Record Not Found")
def menu(self):
while True:
print("\nMenu:")
print("1. Create")
print("2. Display")
print("3. Search")
print("4. Modify")
print("5. Delete")
print("6. Exit")
choice = int(input("Enter your choice (1-6): "))
if choice == 1:
self.create()
elif choice == 2:
self.display()
elif choice == 3:
rno = int(input("Enter roll number: "))
self.search(rno)
elif choice == 4:
self.modify()
elif choice == 5:
self.delete()
elif choice == 6:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
filename = "STUDENT.DAT"
sf = StudentFile(filename)
sf.menu()
Output
11. 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
#Read: must read the entire file and display it on the
screen.
#Write: must take valid input from the user and write
into the file.
#Search: must display the details of those students
whose name is entered as the parameter to the
Search() function.
Sol:- Code
import csv
class StudentCSV:
def __init__(self, filename):
self.filename = filename
def read(self):
try:
with open(self.filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(','.join(row))
except FileNotFoundError:
print("File not found.")
def write(self, rno, name, phone):
with open(self.filename, 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([rno, name, phone])
print("Record written successfully.")
def menu(self):
while True:
print("\nMenu:")
print("a. Read")
print("b. Write")
print("c. Search")
print("d. Exit")
choice = input("Enter your choice (a-d): ")
if choice == 'a':
self.read()
elif choice == 'b':
rno = int(input("Enter roll number: "))
name = input("Enter name: ")
phone = input("Enter phone number: ")
self.write(rno, name, phone)
elif choice == 'c':
name = input("Enter name to search: ")
self.search(name)
elif choice == 'd':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
filename = "student.csv"
sc = StudentCSV(filename)
sc.menu()
Output
12. 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
#Read: must read the entire file and display it on the
screen.
#Write: must take valid input from the user and write
into the file.
#Modify: must ask roll number of the student and
modify the remaining details after taking confirmation
from the user.
#Delete: must ask roll number of the student and
delete the record after taking confirmation from the
user.
Sol:- Code
import csv
def read_file(filename):
with open(filename, 'r', newline='') as file:
reader = csv.reader(file)
for row in reader:
print(','.join(row))
found = False
for i, row in enumerate(rows):
if row[0] == roll_number:
print("Existing Record:")
print(','.join(row))
print("Enter new details:")
name = input("Enter new name: ")
phone = input("Enter new phone number: ")
rows[i] = [roll_number, name, phone]
found = True
break
if found:
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(rows)
print("Record modified successfully.")
else:
print("Record not found.")
if found:
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(rows)
print("Record deleted successfully.")
else:
print("Record not found.")
while True:
print("\nMenu:")
print("1. Read")
print("2. Write")
print("3. Modify")
print("4. Delete")
print("5. Exit")
Sol:- Code
class UserDatabase:
def __init__(self, filename):
self.filename = filename
def display_all(self):
try:
with open(self.filename, 'r') as file:
for i, line in enumerate(file, 1):
entry = line.strip().split(',')
print(f"Record {i}: User ID: {entry[0]},
Password: {entry[1]}")
except FileNotFoundError:
print("File not found.")
def menu(self):
while True:
print("\nMenu:")
print("a. Create")
print("b. Display All")
print("c. Search")
print("d. Exit")
choice = input("Enter your choice (a-d): ")
if choice == 'a':
userid = input("Enter user ID: ")
password = input("Enter password: ")
self.create(userid, password)
elif choice == 'b':
self.display_all()
elif choice == 'c':
userid = input("Enter user ID to search: ")
self.search(userid)
elif choice == 'd':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
filename = "id.csv"
ud = UserDatabase(filename)
ud.menu()
Output
MySQL
16. Consider the following tables GAMES and PLAYER
and answer (b) and (c) parts of this question:
Sol:- Code
db_conn.execute('''CREATE TABLE EMP
(Empno INTEGER PRIMARY KEY,
Ename TEXT,
Age INTEGER,
Gender TEXT,
Salary REAL);''')
print("Table EMP created successfully.")
d. Insert 5 records into EMP table
Sol:- Code
emp_data = [
(1, 'John Doe', 30, 'M', 50000.0),
(2, 'Jane Smith', 28, 'F', 45000.0),
(3, 'Michael Johnson', 35, 'M', 60000.0),
(4, 'Emily Brown', 32, 'F', 55000.0),
(5, 'David Wilson', 33, 'M', 58000.0)
]
db_conn.executemany('INSERT INTO EMP
(Empno, Ename, Age, Gender, Salary)
VALUES (?, ?, ?, ?, ?)', emp_data)
db_conn.commit()
print("Records inserted successfully.")
e. Display all the records of EMP table whose Empno is
entered by the user.
Sol:- Code
empno = int(input("Enter Empno to display records: "))
cursor = db_conn.execute(f"'SELECT * FROM EMP WHERE
Empno = {empno}"')
row = cursor.fetchone()
if row:
print("Empno:", row[0])
print("Ename:", row[1])
print("Age:", row[2])
print("Gender:", row[3])
print("Salary:", row[4])
else:
print("No record found for the entered Empno.")
db_conn.close()
Output
20. Perform the following operations on EMP table:
Output