Computer Scinece Practical File
Computer Scinece Practical File
Practical File
Session 2024-25
Submitted by
Name: Kartik gupta
Class Sec: 12th- B
Subject Teacher: Anshu Sharma
School: Vivekanand public school
Roll No:
INDEX
Functions- INT
#Write a function that converts euros to Indian rupees using
a given conversion rate.
Python code:
def convert_to_rupees(euroAmount, conversionRate):
return amountInRupee
Output:
FUNCTION - STRING
#Write a function that counts the number of
consonants in a string.
Python Code:
def count_consonants(string):
consonants = "bcdfghjklmnpqrstvwxyz"
return count
Output:
FUNCTION - LIST
#Write a function to find the maximum and minimum
number from a list.
Python Code:
def find_max_min(numbers):
Output:
FUNCTION - TUPLE
#Create a function that checks a valid email-password
pair.
Python code:
Output:
FUNCTION - DICTIONARY
Python Code:
def update_dict(data, key, newValue):
data[key] = newValue
Output:
DATA FILE HANDLING - TEXT FILES
#WAP that reads a txt file “story.txt" and do the following
1. ) count the total characters
2.) Count total lines
3.) Count total words
4.) Count total words in each line
5.) Count the no of uppercase lowercase and digits in file.
6.) Count the occurrence of "me" and "my" words in the file.
7.) Count the no. of lines starts with "the".
8.) Count the word that ends with "Y"
9.) Count the words that starts with vowels
10. ) display the sum the digits present in the file
11.) Display total vowel and consonants in the file .
12.) copy the content of story.txt to st"st.txt"
13.) Search the given word in the text file and display its
occurrences and position
14.) Replace "I" with "s" where ever it appears.
Python Code:
def text_file_analysis(file_path):
try:
content = file.read()
file.seek(0)
lines = file.readlines()
total_characters = len(content)
total_lines = len(lines)
words = content.split()
total_words = len(words)
me_count = content.lower().split().count('me')
my_count = content.lower().split().count('my')
sum_of_digits = sum(digits_in_content)
# 11. Count total vowels and consonants
st_file.write(content)
word_occurrences = 0
word_positions = []
if word.strip('.,!?;"\'').lower() == search_word.lower():
word_occurrences += 1
replaced_file.write(replaced_content)
print(f"Digits: {digit_count}")
except Exception as e:
# Main execution
if __name__ == "__main__":
text_file_path = 'story.txt'
text_file_analysis(text_file_path)
Output:
# Write a Python program that reads a file named letter.txt,
counts all the words, and displays the words that have
exactly 5 characters.
Python Code:
def count_five_letter_words(file_path):
try:
content = file.read()
words = content.split()
total_words = len(words)
except FileNotFoundError:
except Exception as e:
# Main execution
if __name__ == "__main__":
text_file_path = 'letter.txt'
count_five_letter_words(text_file_path)
Output:
Function-argument
# Function that takes a list as an argument and prints
each element
Python Code:
# Function that takes a list as an argument and prints each element
def print_list_elements(my_list):
print(element)
# Function that takes a list and returns the sum of its elements
def sum_of_list(my_list):
return sum(my_list)
my_list.append(item)
print("List elements:")
print_list_elements(numbers)
total_sum = sum_of_list(numbers)
append_to_list(numbers, 50)
print_list_elements(numbers)
Output:
File handling- Binary File
# Menu-Driven Program for List Operations on a
Binary File
Python Code:
import pickle
pickle.dump(data_list, file)
def read_list_from_file(filename):
try:
data_list = pickle.load(file)
return data_list
except FileNotFoundError:
return []
except EOFError:
print("File is empty.")
return []
def display_list(data_list):
if not data_list:
else:
print("\nList Contents:")
print(f"{i}. {item}")
"""Searches for an item in the list and displays its index if found."""
if item in data_list:
index = data_list.index(item)
else:
data_list[index] = new_item
else:
print("Invalid index.")
def menu_list():
filename = 'list_data.bin'
data_list = read_list_from_file(filename)
while True:
print("\nMenu:")
print("6. Exit")
if choice == '1':
data_list.append(item)
write_list_to_file(filename, data_list)
display_list(data_list)
del_item = data_list.pop(index)
write_list_to_file(filename, data_list)
else:
print("Invalid index.")
search_item_in_list(data_list, item)
display_list(data_list)
write_list_to_file(filename, data_list)
else:
print("Invalid index.")
print("Exiting program.")
break
else:
if __name__ == "__main__":
menu_list()
Output:
#File Content for Dictionary Operations:
dict_operations.py
Python Code:
# dict_operations.py
import pickle
import os
def initialize_dict_file(filename):
if not os.path.isfile(filename):
sample_dict = {
"name": "Alice",
"age": "30",
"city": "Wonderland"
pickle.dump(sample_dict, file)
pickle.dump(data_dict, file)
def read_dict_from_file(filename):
try:
data_dict = pickle.load(file)
return data_dict
except FileNotFoundError:
return {}
except EOFError:
return {}
def display_dict(data_dict):
if not data_dict:
print("\nDictionary Contents:")
print(f"{key}: {value}")
"""Searches for a key in the dictionary and displays its value if found."""
if key in data_dict:
else:
def menu_dict():
filename = 'dict_data.bin'
initialize_dict_file(filename)
data_dict = read_dict_from_file(filename)
while True:
print("\nMenu:")
print("5. Exit")
data_dict[key] = value
write_dict_to_file(filename, data_dict)
display_dict(data_dict)
if key in data_dict:
del data_dict[key]
write_dict_to_file(filename, data_dict)
else:
search_key_in_dict(data_dict, key)
print("Exiting program.")
break
else:
if __name__ == "__main__":
menu_dict()
Output:
File handling –C.S.V File
Python Code:
# csv_operations.py
import csv
import os
def initialize_csv_file(filename):
if not os.path.isfile(filename):
writer = csv.writer(file)
if not os.path.isfile(filename):
return
reader = csv.reader(file)
print(", ".join(row))
def add_record(filename):
writer = csv.writer(file)
def search_record(filename):
found = False
reader = csv.reader(file)
if row[0] == id_to_search:
print("Record found:")
print(", ".join(row))
found = True
break
if not found:
def menu_csv():
filename = 'records.csv'
initialize_csv_file(filename)
while True:
print("\nMenu:")
print("4. Exit")
display_csv(filename)
add_record(filename)
search_record(filename)
print("Exiting program.")
break
else:
if __name__ == "__main__":
menu_csv()
Output:
MYSQL: - SINGLE TABLE BASED-1
# Do SQL Queries Consider the following table:
iv) Display activity name, Participants Num from the above table.
vi) Display all records where prize money is less than 10000.
SINGLE TABLE BASED- 2
BankDB Tables:
Table: TRANSACT
TRNO ANO AMOUNT TYPE DOT
ACCOUNT Table:
TRANSACT Table:
Queries on BankDB:
(i) To display details of all transactions of TYPE Withdraw from
TRANSACT table:
(ii) To display ANO and AMOUNT of all Deposit and Withdrawals done
in the month of ‘May’ 2017:
(iv) To display ANO, ANAME, AMOUNT, and DOT of those persons from
ACCOUNT and TRANSACT tables that have done transactions less than
or equal to 3000:
VEHICLE Table:
TRAVEL Table:
Queries on TravelDB:
(i) Display CNO, CNAME, and TRAVELDATE from the TRAVEL table in
descending order of CNO:
(ii) Display the CNAME of all customers from the TRAVEL table who
are traveling by vehicle with code V01 or V02:
(iii) Display the CNO and CNAME of those customers from the TRAVEL
table who traveled between certain dates:
(iv) Display all details from the TRAVEL table for customers who have
travelled more than 120 KM, ordered by NOP:
Natural Join:
FROM Employees NATURAL Joining Departments;
Output:
PYTHON AND SQL CONNECTIVITY
def connect_to_db():
try:
connection = mysql.connector.connect(
host='localhost',
user='root',
password='1234'
if connection.is_connected():
print("Connected to MySQL server.")
return connection
except Error as e:
print(f"Error: {e}")
return None
def create_database_and_table(connection):
try:
cursor = connection.cursor()
cursor.execute("USE my_database")
cursor.execute("""
""")
except Error as e:
print(f"Error: {e}")
def create_record(cursor):
try:
except Error as e:
print(f"Error: {e}")
def read_records(cursor):
try:
rows = cursor.fetchall()
print("\nAll Records:")
except Error as e:
print(f"Error: {e}")
def read_selected_record(cursor):
try:
row = cursor.fetchone()
if row:
except Error as e:
print(f"Error: {e}")
def update_record(cursor):
try:
except Error as e:
print(f"Error: {e}")
def delete_record(cursor):
try:
except Error as e:
print(f"Error: {e}")
def main():
connection = connect_to_db()
if connection is None:
return
create_database_and_table(connection)
cursor = connection.cursor()
while True:
print("\nMenu:")
print("6. Exit")
if choice == '1':
create_record(cursor)
connection.commit()
read_records(cursor)
read_selected_record(cursor)
update_record(cursor)
connection.commit()
elif choice == '5':
delete_record(cursor connection.commit()
print("Exiting...")
break
else:
cursor.close()
connection.close()
if __name__ == "__main__":
main()
Output: