COMPUTER SCIENCE
PRACTICAL FILE
G.D. GOENKA PUBLIC SCHOOL , SECTOR 22, ROHINI
NAME : KAVYANSH GUPTA
CLASS : 12 B
ROLL NO : 12
CERTIFICATE
This is to certify that __________________________of class XII (session
2023-24) of G.D. Goenka Public School, Sector- 22, Rohini has completed
his practical file work for submission as required by CBSE for the subject
Computer Science (083).
It is certified that, this project/practical file is an original piece of work and
completed under my guidance and as per instructions given by CBSE.
_______________
Project Mentor
________________
Examiner
_____________Principal
INDEX
[Link]. Program Teacher’s
signature
1. Write a code to get a string from
a given string where all
occurrences of its first character
have been changed to '*',
except the first character itself
using function.
2. Write a code to swap commas
and dots in a user defined string
using function.
3. Write a code to find all duplicate
characters in a user defined
string using function.
4. Write a code LeftShift(lst, x) in
Python which accepts numbers
in a list (lst) and all the elements
of the list should be shifted to
left according to the value of x.
5. Write a code using function to
identify whether a given number
is Armstrong number or not.
6. Write a program using function
and container function that
groups anagrams together using
dictionaries:
words = ['eat', 'tea', 'tan', 'ate',
'nat', 'bat']
# Output: {'aet': ['eat', 'tea', 'ate'],
'ant': ['tan', 'nat'], 'abt': ['bat']}
7. Write a code to generate a
random numbers between 1 and
6 which simulates just like a dice
8. Write a code to determine
whether the given string is
palindrome or not using function.
9. Write a code to determine the
mean,median and mode of all
the elements of a list using
functions.
10. Write a code to read data from a
text file [Link], and display
word which have
maximum/minimum characters.
11. Write a code to read data from a
text file [Link], and display
each words with number of
vowels and consonants.
12. Write a code to read data from a
text file [Link], and convert
all uppercase characters to
lowercase and vice versa.
13. Write a code which accepts
author name as parameter and
count and return number of
books by the given author are
stored in the binary file
“[Link]”
14. Write a code to display the
record of a particular product
from [Link] whose code is
passed as an argument. The file
contains product code and price.
15. Write a code considering a
binary file ‘[Link]’ having
structure [admnno, Name,
Percentage]. Create a function
that would read all content of file
and display the details of those
students whose percentage is
above 90. Also display the
number of students scoring
above 90% and above 80%
separately.
16. Write a program to read all
content of “[Link]” and
display records of only those
books whose author is given by
user. Records stored in students
is in format: Book id, book name,
author, edition, price
17. Write a program to calculate the
percentage of all the students
given in the file ”[Link]”.
Records in marks .csv should be
in the following format
Rollno, Name, marks
18. Write a program to calculate the
sum of all the marks given in the
file ”[Link]”. Records in
marks .csv should be in the
following format
Admin no,Rollno, Name, marks
Create a separate function to
show the detail of the student
who scored the highest marks ,
lowest marks, search specific
admin no.
19. Write a menu driven code using
functions Addflight(), Delete
flight(), Display flight() to
implement the Stack. The
program will store the details of
the flights i.e. flight number, flight
name and fare.
20. Write a code to display the size
of a text file in bytes.
21. Write a program having add and
remove functions to add new
client and delete existing client
from a list "client detail"
displaying push and pop
operations on the stack. Also
search a specific client using
his/her [Link] client detail list
should include id, client name
and contact no.
22. Write command to calculate the
max, min, average, sum of
marks from student table having
columns as rollno, name, class,
marks, city.
23. Write a code to insert a new
record in table student. The
function should pass values as
parameters.(refer table of Q21)
24. Write a code to delete a record
in the student table according to
the rollno passed as
parameter.(refer table of Q21)
25. Write a code to read the student
marks as parameter and update
the record in student table .(refer
table of Q21)
1. Write a code to get a string from a given string where all occurrences of its
first character have been changed to '*',
except the first character itself using function.
s = "banana"
new_s = s[0]
for c in s[1:]:
if c == s[0]:
new_s += '*'
else:
new_s += c
print(new_s)
2. Write a code to swap commas and dots in a user defined string using
function.
def swap_commas_dots(s):
s = [Link](',', '-')
s = [Link]('.', ',')
s = [Link]('-', '.')
return s
text = "Hello, world. I am learning Python."
print(swap_commas_dots(text))
3. Write a code to find all duplicate characters in a user defined string using
function.
def find_duplicates(s):
duplicates = set()
for c in s:
if [Link](c) > 1:
[Link](c)
return duplicates
print(find_duplicates("programming"))
Output :
4. Write a code LeftShift(lst, x) in Python which accepts numbers in a list
(lst) and all the elements of the list should be shifted to left according to
the value of x.
def LeftShift(lst, x):
n = len(lst)
x = x % n # handle x > length
return lst[x:] + lst[:x]
print(LeftShift([1,2,3,4,5], 2))
Output:
[Link] a code using function to identify whether a given number is Armstrong
number or not.
def is_armstrong(n):
num = n
order = len(str(n))
sum_ = 0
while n > 0:
digit = n % 10
sum_ += digit ** order
n = n // 10
return sum_ == num
print(is_armstrong(153))
print(is_armstrong(123))
Output:
[Link] a program using function and container function that groups anagrams
together using dictionaries:
words = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']
def group_anagrams(words):
anagram_dict = {}
for word in words:
key = ''.join(sorted(word))
if key in anagram_dict:
anagram_dict[key].append(word)
else:
anagram_dict[key] = [word]
return anagram_dict
words = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']
print(group_anagrams(words))
Output :
7. Write a code to generate a random numbers between 1 and 6 which simulates
just like a dice
import random
def roll_dice():
return [Link](1, 6)
def dice_simulator():
print("Welcome to Dice Simulator!")
while True:
input("Press Enter to roll the dice...")
dice1 = roll_dice()
dice2 = roll_dice()
total = dice1 + dice2
print(f"You rolled: {dice1} and {dice2} (Total = {total})")
choice = input("Do you want to roll again? (y/n): ")
if [Link]() != 'y':
print("Thanks for playing!")
break
dice_simulator()
Output :
8. Check palindrome
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("madam"))
print(is_palindrome("hello"))
9. Mean, Median, Mode
from statistics import mean, median, mode
def calculate_stats(lst):
return mean(lst), median(lst), mode(lst)
lst = [1,2,2,3,4]
print(calculate_stats(lst)) # Output: (2.4, 2, 2)
10. Write a code to read data from a text file [Link], and display word which
have maximum/minimum characters.
def max_min_word():
with open("[Link]", "r") as f:
words = [Link]().split()
max_word = min_word = words[0]
for word in words:
if len(word) > len(max_word):
max_word = word
if len(word) < len(min_word):
min_word = word
print("Word with maximum characters:", max_word)
print("Word with minimum characters:", min_word)
max_min_word()
11. Write a code to read data from a text file [Link], and display each words with
number of vowels and consonants.
def vowel_consonant_count():
vowels = "aeiouAEIOU"
with open("[Link]", "r") as f:
words = [Link]().split()
for word in words:
v_count = sum(1 for c in word if c in vowels)
c_count = sum(1 for c in word if [Link]() and c not in vowels)
print(f"{word}: Vowels={v_count}, Consonants={c_count}")
vowel_consonant_count()
12. Write a code to read data from a text file [Link], and convert all uppercase
characters to lowercase and vice versa.
def swap_case_file():
with open("[Link]", "r") as f:
data = [Link]()
print([Link]())
swap_case_file()
13. Write a code which accepts author name as parameter and count and return
number of books by the given author are stored in the binary file “[Link]”)
def count_books_by_author():
author = input("Enter author name: ")
count = 0
try:
with open("[Link]", "r") as file:
for line in file:
# split each line by comma
book = [Link]().split(",")
# book[1] is author
if book[1] == author:
count += 1
print(f"Number of books by {author}: {count}")
except FileNotFoundError:
print("[Link] not found.")
14. Write a code to display the record of a particular product from [Link] whose
code is passed as an argument. The file contains product code and price
def display_product(product_code):
file = open("[Link]", "r")
found = False
for line in file:
line = [Link]()
if not line: # skip empty lines
continue
# Each line has "product_code price"
parts = [Link]()
if len(parts) != 2:
continue
code, price = parts
if code == product_code:
print(f"Product Code: {code}, Price: {price}")
found = True
break
if not found:
print(f"No record found for product code: {product_code}")
[Link]()
product_code = input("Enter the product code: ")
display_product(product_code)
15. Write a code considering a binary file ‘[Link]’ having structure [admnno,
Name, Percentage]. Create a function that would read all content of file and
display the details of those students whose percentage is above 90. Also display
the number of students scoring above 90% and above 80% separately.
import pickle
def display_top_students():
above_90 = 0
above_80 = 0
f = open("[Link]", "rb")
students = [Link](f)
[Link]()
print("Students with percentage above 90:")
for student in students:
admnno, name, percentage = student
if percentage > 90:
print(f"Admn No: {admnno}, Name: {name}, Percentage: {percentage}")
above_90 += 1
if percentage > 80:
above_80 += 1
print("Number of students scoring above 90%:", above_90)
print("Number of students scoring above 80%:", above_80)
display_top_students()
16. Write a program to read all content of “[Link]” and display records of
only those books whose author is given by user. Records stored in students is in
format: Book id, book name, author, edition, price
import csv
author_name = input("Enter author name: ")
file = open("[Link]", "r")
reader = [Link](file)
for row in reader:
if row[2] == author_name:
print("Book ID:", row[0], "Book Name:", row[1], "Author:", row[2], "Edition:", row[3], "Price:",
row[4])
[Link]()
17. Write a program to calculate the percentage of all the students given in the
file ”[Link]”. Records in marks .csv should be in the following format
Rollno, Name, marks
import csv
file = open("[Link]", "r")
reader = [Link](file)
total_marks = 500 # assuming total marks is 500
for row in reader:
rollno = row[0]
name = row[1]
marks = int(row[2])
percentage = (marks * 100) / total_marks
print("Rollno:", rollno, "Name:", name, "Percentage:", percentage)
[Link]()
18. Write a program to calculate the sum of all the marks given in the file
”[Link]”. Records in marks .csv should be in the following format
Admin no,Rollno, Name, marks
Create a separate function to show the detail of the student who scored the
highest marks , lowest marks, search specific admin no.
import csv
file = open("[Link]", "r")
reader = [Link](file)
total_marks = 100 # assuming marks are out of 100
for row in reader:
rollno = row[1]
name = row[2]
marks = int(row[3])
percentage = (marks * 100) / total_marks
print("Rollno:", rollno, "Name:", name, "Percentage:", percentage)
[Link]()
19. Write a menu driven code using functions Addflight(), Delete flight(), Display
flight() to implement the Stack. The program will store the details of the flights i.e.
flight number, flight name and fare.
flights = []
def Addflight():
flight_number = input("Enter flight number: ")
flight_name = input("Enter flight name: ")
fare = input("Enter fare: ")
flight = [flight_number, flight_name, fare]
[Link](flight) # push onto stack
print("Flight added.")
def Deleteflight():
if len(flights) == 0:
print("No flights to delete.")
else:
flight = [Link]() # pop from stack
print("Deleted flight:")
print("Flight number:", flight[0], "Flight name:", flight[1], "Fare:", flight[2])
def Displayflight():
if len(flights) == 0:
print("No flights available.")
else:
print("Flights in stack:")
for flight in reversed(flights): # display top to bottom
print("Flight number:", flight[0], "Flight name:", flight[1], "Fare:", flight[2])
while True:
print("\n1. Add Flight")
print("2. Delete Flight")
print("3. Display Flights")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
Addflight()
elif choice == "2":
Deleteflight()
elif choice == "3":
Displayflight()
elif choice == "4":
print("Exiting...")
break
else:
print("Invalid choice. Try again.")
20. Write a code to display the size of a text file in bytes.
file = open("[Link]", "r")
size = 0
for i in file: # i is each line
size += len(i) # count all characters in the line
[Link]()
print("Size of [Link] is", size, "bytes")
21. Write a program having add and remove functions to add new client and delete
existing client from a list "client detail" displaying push and pop operations on the stack.
Also search a specific client using his/her [Link] client detail list should include id, client
name and contact no.
client_detail = []
def add():
cid = input("Enter client id: ")
name = input("Enter client name: ")
contact = input("Enter contact no: ")
client_detail.append([cid, name, contact])
print("Client added.")
def remove():
if len(client_detail) == 0:
print("No clients to remove.")
else:
client = client_detail.pop()
print("Removed client:")
print("ID:", client[0], "Name:", client[1], "Contact:", client[2])
def search():
cid = input("Enter client id to search: ")
for client in client_detail:
if client[0] == cid:
print("Client found:")
print("ID:", client[0], "Name:", client[1], "Contact:", client[2])
return
print("Client not found.")
def display():
if len(client_detail) == 0:
print("No clients in stack.")
else:
print("Clients in stack:")
for client in reversed(client_detail):
print("ID:", client[0], "Name:", client[1], "Contact:", client[2])
print("1. Add Client")
print("2. Remove Client")
print("3. Search Client")
print("4. Display Clients")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == "1":
add()
elif choice == "2":
remove()
elif choice == "3":
search()
elif choice == "4":
display()
elif choice == "5":
print("Exiting...")
else:
print("Invalid choice. Try again.")
22. Write command to calculate the max, min, average, sum of marks from student table
having columns as rollno, name, class, marks, city.
SELECT MAX(marks) FROM student;
SELECT MIN(marks) FROM student;
SELECT AVG(marks) FROM student;
SELECT SUM(marks) FROM student;
23. Write command to calculate the max, min, average, sum of marks from student table
having columns as rollno, name, class, marks, city.
import [Link]
conn = [Link](
host="localhost",
user="root",
password="Kavyansh@2008",
database="school"
)
cursor = [Link]()
sql = "INSERT INTO student (admin_no, rollno, name, class, marks, city) VALUES (1947, 12,
'Kavyansh', '12B', 99, 'DELHI')"
[Link](sql)
[Link]()
print("Record inserted successfully.")
24. Write a code to delete a record in the student table according to the rollno
passed as parameter.(refer table of Q21)
import [Link]
conn = [Link](
host="localhost",
user="root",
password="Kavyansh@2008",
database="school"
)
cursor = [Link]()
sql = "UPDATE student SET marks = 95 WHERE rollno = '102'"
[Link](sql)
[Link]()
print("Record updated successfully.")
25. Write a code to read the student marks as parameter and update the record in
student table .(refer table of Q21)
import [Link]
conn = [Link](
host="localhost",
user="root",
password="Kavyansh@2008",
database="school"
)
cursor = [Link]()
sql = "UPDATE student SET marks = 95 WHERE rollno = '102'"
[Link](sql)
[Link]()
print("Record updated successfully.")