0% found this document useful (0 votes)
83 views29 pages

Practical File Class 12 2025

Uploaded by

jainlavya12
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)
83 views29 pages

Practical File Class 12 2025

Uploaded by

jainlavya12
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/ 29

MAHARAJA AGRASEN MODEL SCHOOL

PITAMPURA , DELHI-34

COMPUTER SCIENCE
PRACTICAL FILE
SESSION- 2025-26

SUBMITTED BY: Lavya Jain


CLASS: XII-B
ROLL NUMBER: 11
INDEX

USER DEFINED FUNCTIONS

1 Write a program to calculate the sum of the digits of a number using


functions.
2 Write a function that takes a list of numbers as an argument and return
the sum of all numbers which are divisible by 5. Also write a complete
Python program to call this function.
3 Write a function that takes a string as an argument and return
Palindrome if the string is a palindrome otherwise return Not A
Palindrome. Also write a complete Python program to call this function.
4 Write a Python function that takes a list of strings as an argument and
displays the strings which starts with “S” or “s”. Also write a program to
invoke this function.
5 Write Python script to create a dictionary with players name and their
score. Write a function that accepts this dictionary as an argument and
displays the name of the player with the highest score.
TEXT FILES

6 Read a text file line by line and display each word separated by a #.
7 Read a text file line by line and display lines starting with ‘A’.
8 Remove all the lines that contain the character `a' in a file and write it to
another file.
9 Write a program to read text file and print and count four letter words.
10 Write a program that reads a text file and count the number of words
ending with “ing”.
BINARY FILES

11 Create a binary file with name and roll number. Search for a given roll
number and display the name, if not found display appropriate message.
12 Create a binary file with roll number, name and marks. Input a roll
number and increase the marks by 10.
13 Create a binary file GIFT having GiftID, gift name, remarks and price
and display details of those gifts, which has remarks as “ÖN
DISCOUNT”.
14 Create a binary file School having SchoolCode, Name and
NoOfTeachers and display details of those schools where
NoOfTeachers>200.
15 Create a binary file MULTIPLEX having MNo, Mname and Type and
delete those record where Mname starts with ‘S’.
CSV FILES

16 Write a Python script to read a VEHICLE.CSV file containing


Vehicle_Id, VehicleName, Manufacturing Year having comma as a
delimiter. Display those records for the year 2024.
17 Write a Python script to read a ITEM.CSV file containing ItemNo,
Quantity, Price. Display RollNo and total amount of all items.
STACKS

18 Write a menu driven Python program to implement a stack using a list


data-structure storing data: book name, no. of copies, cost.
19 Write a menu driven Python program to implement a stack storing
employee number, name and basic using a list data-structure.
MYSQL PYTHON CONNECTIVITY

20 Consider a table DOCTOR with the following data:

TABLE: DOCTOR

SE
ID NAME DEPT EXPERIENCE Consultation Fees
X

10
JOHN ENT M 12 1000
1

10
SMITH ORTHPEDIC M 5 350
4

10
GEORGE CARDIOLOGY M 10 800
7
11
LARA SKIN F 3 250
4

10
K GEORGE MEDICINE F 9 850
9

10
JOHNSON ORTHPEDIC M 10 1000
5

11
LUCY ENT F 3 250
7

11
BILL MEDICINE F 12 1200
1

13
MORPHY ORTHPEDIC M 15 1500
0

Write a menu driven Python code for the following:

1. Insert a new record


2. Delete a record with consultation fees greater than 300
3. Increase the consultation fees by 200 for doctors whose
experience is greater than 10 years.
4. Display records of all female employees.
5. Display all records
21

Write python code for the following;-

1. Display all records


2. Delete a record
3. Display records of students with average > 50
4. Display name , subject , marks of students in first division
5. Increase average by 5 whose average is less than 40
22

Write python code for the following ;-

1. Add a record
2. Display records of people living in south area
3. Display all names starting with A.
4. Increase the salary of people by 1000 whose salary is less than
4000
5. Display phone numbers starting with 98.
23

Write Python Code for the following;-

1. Display all records


2. Delete records whose price is more than 500
3. Display total quantities of books
4. Delete a record of specific book_id
5. Display records of books with qty more than 40.

USER DEFINED FUNCTIONS


PROGRAM 1: Write a program to calculate the sum of the digits of a number
using functions.

CODE:
def sum_digits(number):
sum = 0
for digit in str(number):
sum += int(digit)
return sum

number = 12345
digit_sum = sum_digits(number)
print("The sum of the digits of",number "is" digit_sum)

OUTPUT:

PROGRAM 2: Write a function that takes a list of numbers as an argument and return
the sum of all numbers which are divisible by 5. Also write a complete Python
program to call this function.
CODE:
def sum_divisible_by_5(numbers):
total = 0
for num in numbers:
if num % 5 == 0:
total += num
return total

input_string = input("Enter numbers separated by spaces: ")

number_list = []
for item in input_string.split():
number_list.append(int(item))
result = sum_divisible_by_5(number_list)
print("Sum of numbers divisible by 5:", result)

OUTPUT:

PROGRAM 3: Write a function that takes a string as an argument and return


Palindrome if the string is a palindrome otherwise return Not A Palindrome. Also
write a complete Python program to call this function.
CODE:
def check_palindrome(text):
text = text.replace(" ", "").lower()
if text == text[::-1]:
return "Palindrome"
else:
return "Not A Palindrome"

user_input = input("Enter a string: ")


result = check_palindrome(user_input)
print("Result:", result)

OUTPUT:

PROGRAM 4: Write a Python function that takes a list of strings as an argument and
displays the strings which starts with “S” or “s”. Also write a program to invoke this
function.
CODE:
def display_s_words(word_list):
print("Words starting with 'S' or 's':")
for word in word_list:
if word.startswith('S') or word.startswith('s'):
print(word)

input_string = input("Enter words separated by spaces: ")


words = input_string.split()
display_s_words(words)
OUTPUT:

PROGRAM 5: Write Python script to create a dictionary with players name and their
score. Write a function that accepts this dictionary as an argument and displays the
name of the player with the highest score.
CODE:
def highest_scorer(scores):
highest = max(scores, key=scores.get)
print("Player with the highest score:", highest)

players = {}
n = int(input("How many players? "))
for i in range(n):
name = input("Enter player name: ")
score = int(input("Enter score: "))
players[name] = score

highest_scorer(players)
OUTPUT:

TEXT FILES

PROGRAM6: Read a text file line by line and display each word separated by a #

CODE:
def read():
with open("/content/drive/MyDrive/text/demo.txt", "r") as f:
for line in f:
for word in line.split(): # line is already a string, no need for .read()
print(word, end="#")

read()

SAMPLE TEXT FILE :

OUTPUT:

PROGRAM 7: Read a text file line by line and display lines starting with ‘A’.

CODE:
def read_lines_starting_with_A():
with open("/content/drive/MyDrive/text/demo.txt", "r") as f:
for line in f:
if line.strip().startswith('A'):
print(line.strip())

read_lines_starting_with_A()

SAMPLE TEXT FILE:

OUTPUT:

PROGRAM 8: Remove all the lines that contain the character `a' in a file and write it
to another file.

CODE:
def remove_lines_with_a():
with open("/content/drive/MyDrive/text /demo.txt", "r") as f1,
open("/content/drive/MyDrive/text /cleaned.txt", "w") as f2:

for line in f1:


if 'a' not in line:
f2.write(line)

remove_lines_with_a()

SAMPLE TEXT FILE:

OUTPUT:

PROGRAM 9: Write a program to read text file and print and count four letter words.

CODE:
def count_four_letter_words():
count = 0
with open("/content/drive/MyDrive/text /demo.txt", "r") as file:
for line in file:
words = line.strip().split()
for word in words:
if len(word) == 4:
print(word)
count += 1
print("Total four-letter words:", count)

SAMPLE TEXT FILE:

OUTPUT:

PROGRAM 10: Write a program that reads a text file and count the number of words
ending with “ing”

CODE:

def count_ing_words():
count = 0
with open("/content/drive/MyDrive/text /demo.txt", "r") as file:
for line in file:
words = line.strip().split()
for word in words:
if word.lower().endswith("ing"):
print(word)
count += 1
print("Total words ending with 'ing':", count)

count_ing_words()

SAMPLE TEXT FILE:

OUTPUT:

BINARY FILES

PROGRAM 11: Create a binary file with name and roll number. Search for a given
roll number and display the name, if not found display appropriate message.
CODE:
import pickle
def write_to_file():
f = open('/content/drive/MyDrive/binary files/student.dat', 'wb')
while True:
name = input('Enter the name: ')
roll_no = int(input('Enter the roll number: '))
rec = [name, roll_no]
pickle.dump(rec, f)
print('Record saved...')
ans = input('Do you wish to continue? (y/n): ')
if ans.lower() == 'n':
break
f.close()
def search_roll_number():
found = False
try:
f = open('/content/drive/MyDrive/binary files/student.dat', 'rb')
search_roll = int(input("Enter roll number to search: "))
while True:
try:
rec = pickle.load(f)
if rec[1] == search_roll:
print("Name found:", rec[0])
found = True
break
except EOFError:
break
f.close()
if not found:
print("Roll number not found.")
except FileNotFoundError:
print("File not found.")
write_to_file()
search_roll_number()
OUTPUT:
PROGRAM 12: Create a binary file with roll number, name and marks. Input a roll
number and increase the marks by 10.
CODE:
import pickle
def write_to_file():
with open('/content/drive/MyDrive/binary files/student.dat', 'wb') as f:
while True:
roll = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = int(input("Enter marks: "))
rec = [roll, name, marks]
pickle.dump(rec, f)
print("Record saved.")
cont = input("Do you want to add another record? (y/n): ")
if cont.lower() == 'n':
break
def increase_marks():
updated = False
new_data = []
try:
with open('/content/drive/MyDrive/binary files/student.dat', 'rb') as f:
while True:
try:
rec = pickle.load(f)
new_data.append(rec)
except EOFError:
break
except FileNotFoundError:
print("File not found.")
return
roll_search = int(input("Enter roll number to increase marks: "))
for i in range(len(new_data)):
if new_data[i][0] == roll_search:
new_data[i][2] += 10
print(f"Marks updated for roll number {roll_search}.")
updated = True
break
if not updated:
print("Roll number not found.")
return
with open('/content/drive/MyDrive/binary files/student.dat', 'wb') as f:
for rec in new_data:
pickle.dump(rec, f)
write_to_file()
increase_marks()

OUTPUT:

PROGRAM 13: Create a binary file GIFT having GiftID, gift name, remarks and
price and display details of those gifts, which has remarks as “ÖN DISCOUNT”.

CODE:
import pickle
def write_gift_data():
with open('/content/drive/MyDrive/binary files/GIFT.dat', 'wb') as f:
while True:
gift_id = int(input("Enter Gift ID: "))
gift_name = input("Enter Gift Name: ")
remarks = input("Enter Remarks: ")
price = float(input("Enter Price: "))
rec = [gift_id, gift_name, remarks, price]
pickle.dump(rec, f)
print("Record saved.")
cont = input("Do you want to add another gift? (y/n): ")
if cont.lower() == 'n':
break
def show_discount_gifts():
try:
with open('/content/drive/MyDrive/binary files/GIFT.dat', 'rb') as f:
print("\nGifts with remarks 'ON DISCOUNT':")
found = False
while True:
try:
rec = pickle.load(f)
if rec[2] == "ON DISCOUNT":
print(f"GiftID: {rec[0]}, Name: {rec[1]}, Remarks: {rec[2]}, Price:
{rec[3]}")
found = True
except EOFError:
break
if not found:
print("No gifts found with 'ON DISCOUNT' remarks.")
except FileNotFoundError:
print("File not found.")
write_gift_data()
show_discount_gifts()

OUTPUT:

PROGRAM 14: Create a binary file School having SchoolCode, Name and
NoOfTeachers and display details of those schools where NoOfTeachers>200.
CODE:
import pickle
def write_school_data():
with open('/content/drive/MyDrive/binary files/School.dat', 'wb') as f:
while True:
code = input("Enter School Code: ")
name = input("Enter School Name: ")
teachers = int(input("Enter Number of Teachers: "))
rec = [code, name, teachers]
pickle.dump(rec, f)
print("Record saved.")
cont = input("Do you want to add another school? (y/n): ")
if cont.lower() == 'n':
break
def show_large_schools():
try:
with open('/content/drive/MyDrive/binary files/School.dat', 'rb') as f:
print("\nSchools with more than 200 teachers:")
found = False
while True:
try:
rec = pickle.load(f)
if rec[2] > 200:
print(f"School Code: {rec[0]}, Name: {rec[1]}, Teachers: {rec[2]}")
found = True
except EOFError:
break
if not found:
print("No school has more than 200 teachers.")
except FileNotFoundError:
print("School.dat file not found.")
write_school_data()
show_large_schools()

OUTPUT:
PROGRAM 15: Create a binary file MULTIPLEX having MNo, Mname and Type
and delete those record where Mname starts with ‘S’.
CODE:
import pickle
def write_multiplex_data():
with open('/content/drive/MyDrive/binary files/MULTIPLEX.dat', 'wb') as f:
while True:
mno = int(input("Enter Multiplex Number: "))
mname = input("Enter Multiplex Name: ")
mtype = input("Enter Multiplex Type: ")
rec = [mno, mname, mtype]
pickle.dump(rec, f)
print("Record saved.")
cont = input("Do you want to add another record? (y/n): ")
if cont.lower() == 'n':
break
def delete_mname_starting_with_S():
data = []
try:
with open('/content/drive/MyDrive/binary files/MULTIPLEX.dat', 'rb') as f:
while True:
try:
rec = pickle.load(f)
if not rec[1].startswith('S'):
data.append(rec)
except EOFError:
break
except FileNotFoundError:
print("File not found.")
return
with open('/content/drive/MyDrive/binary files/MULTIPLEX.dat', 'wb') as f:
for rec in data:
pickle.dump(rec, f)
print("Records starting with 'S' have been deleted.")
write_multiplex_data()
delete_mname_starting_with_S()

OUTPUT:
CSV FILES

PROGRAM 16: Write a Python script to read a VEHICLE.CSV file containing


Vehicle_Id, VehicleName, Manufacturing Year having comma as a delimiter. Display
those records for the year 2024.

CODE:

OUTPUT:
PROGRAM 17: Write a Python script to read a ITEM.CSV file containing ItemNo,
Quantity, Price. Display RollNo and total amount of all items.

CODE:

OUTPUT:
STACK
PROGRAM 18: Write a menu driven Python program to implement a stack using a
list data-structure storing data: book name, no. of copies, cost.
CODE:
stack = []
def push():
book = input("Enter book name: ")
copies = int(input("Enter number of copies: "))
cost = float(input("Enter cost: "))
record = [book, copies, cost]
stack.append(record)
print("Book pushed onto stack.\n")
def pop():
if not stack:
print("Stack is empty.")
else:
removed = stack.pop()
print("Popped record:",removed)
def display():
if not stack:
print("Stack is empty.")
else:
print("Current Stack (Top to Bottom):")
for record in reversed(stack):
print(record)
print()
def menu():
while True:
print("----- Stack Menu -----")
print("1. Push")
print("2. Pop")
print("3. Display Stack")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
push()
elif choice == '2':
pop()
elif choice == '3':
display()
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice. Try again.")
menu()

OUTPUT:
PROGRAM 19: Write a menu driven Python program to implement a stack storing
employee number, name and basic using a list data-structure.

CODE:
stack = []
def push():
emp_no = input("Enter Employee Number: ")
name = input("Enter Employee Name: ")
basic = float(input("Enter Basic Salary: "))
record = [emp_no, name, basic]
stack.append(record)
print("Employee record added.")
def pop():
if len(stack) == 0:
print("Stack is empty.")
else:
record = stack.pop()
print("Popped Employee Record:", record)
def display():
if len(stack) == 0:
print("Stack is empty.")
else:
print("Current Stack (Top to Bottom):")
for record in reversed(stack):
print("EmpNo:", record[0], ", Name:", record[1], ", Basic:", record[2])
def menu():
while True:
print("----- Employee Stack Menu -----")
print("1. Push Employee")
print("2. Pop Employee")
print("3. Display Stack")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
push()
elif choice == '2':
pop()
elif choice == '3':
display()
elif choice == '4':
print("Program ended.")
break
else:
print("Invalid choice. Try again.")

menu()

OUTPUT:

You might also like